aggregation framework - MongoDB query selecting documents with distinct fields -


this question has answer here:

imagine have mongodb collection such following, each row corresponds document:

{name:'rick', age:30} {name:'john', age:40} {name:'rick', age:35} {name:'john', age:20} {name:'jeff', age:50} {name:'jeff', age:40} 

some documents have "name" field set same value (2 ricks, 2 johns , 2 jeffs). if 2 or more documents have "name" field set same value, of these want select document highest age. this:

{name:'rick', age:35} {name:'john', age:40} {name:'jeff', age:50} 

is there rick aged 30 , rick aged 35? select rick aged 35! , on...

but how can query like?

db.getcollection('mytest').aggregate({$group:{_id:{"name":"$name"}, age: { $max: "$age" }}})

output:

{     "_id" : {         "name" : "jeff"     },     "age" : 50 }  /* 2 */ {     "_id" : {         "name" : "john"     },     "age" : 40 }  /* 3 */ {     "_id" : {         "name" : "rick"     },     "age" : 35 } 

Comments

Popular posts from this blog

AbotX : How do you create a parallel crawler that stays on and can be added to at run time from new requests -

testing - Detect whether test has failed within fixture -

android - Create single AAR file from multiple modules using Gradle -