node.js - mongodb aggregation get the total number of matched document -


i have following sample docs saved in mongogb, like:

{     name: 'andy',     age: 19,     description: 'aaa aaa aaa' } {     name: 'andy',     age: 17,     description: 'bbb bbb bbb' } {     name: 'leo',     age: 10,     description: 'aaa aaa aaa' } {     name: 'andy',     age: 17,     description: 'ccc ccc ccc' } 

what pipeline should total number of name in each of matched sets? can use sum number next pipe. pipeline have this:

var pip = [     {         $match: { name: 'andy' }     } ] 

and want result like

{     name: 'andy',     age: 19,     description: 'aaa aaa aaa',     total_andy: 3 } {     name: 'andy',     age: 17,     description: 'bbb bbb bbb',     total_andy: 3 } {     name: 'andy',     age: 17,     description: 'ccc ccc ccc',     total_andy: 3 } 

i not clear want. , don't have enough reputation ask in comment. let me have shot @ answering. if answer isn't want, clarify question further , we'll it...

var term1group = {$group :                              {'_id' : '$name'},                             'total_names' : {$sum : 1},                             'ageanddescription' : {$addtoset : {'$age', '$description'}}                     }  var term2unwind = {$unwind : '$ageanddescription'}  var term3project = {$project : {                             _id : 0,                             'name' : '_id',                             'age' : '$ageanddescription.age',                             'description' : '$ageanddescription.description',                             'total_name' : 1                             }  db.collection.aggregate(term1group, term2unwind, term3project); 

haven't tested hopeful work.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -