aggregation framework - MongoDB query selecting documents with distinct fields -
this question has answer here:
- select max() “group by” in mongodb 4 answers
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
Post a Comment