mongodb - mongo group query how to keep fields -
everybody. in mongo group query, result shows key(s) in arguments. how keep first document in each group mysql query group. example:
------------------------------------------------------------------------- | name | age | sex | province | city | area | address | ------------------------------------------------------------------------- | ddl1st | 22 | 纯爷们 | beijing | beijing | chaoyang | qingnianlu | | ddl1st | 24 | 纯爷们 | beijing | beijing | xuhui | zhaojiabanglu | | 24k | 220 | ... | .... | ... | ... | ... | ------------------------------------------------------------------------- db.users.group({key: { name: 1},reduce: function ( curr, result ) { result.count ++ },initial: {count : 0 } })
result:
[ { "name" : "ddl1st", "count" : 1 }, { "name" : "24k", "count" : 1 } ]
how following:
[ { "name" : "ddl1st", "age" : 22, "sex" : "纯爷们", "province" : "beijing", "city" : "beijing", "area" : "chaoyang", "address" : "qingnianlu", "count" : 1 }, { "name" : "24k", "age" : 220, "sex" : "...", "province" : "...", "city" : "...", "area" : "...", "address" : "...", "count" : 1 } ]
if want keep information first matching entries each group, can try aggregating like:
db.test.aggregate({ $group: { _id: '$name', name : { $first: '$name' } age : { $first: '$age' }, sex : { $first: '$sex' }, province : { $first: '$province' }, city : { $first: '$city' }, area : { $first: '$area' }, address : { $first: '$address' }, count: { $sum: 1 } } }
Comments
Post a Comment