想象一下,我有一个MongoDB集合,如下所示,其中每一行对应一个文档:
{name:'rick', age:30}
{name:'john', age:40}
{name:'rick', age:35}
{name:'john', age:20}
{name:'jeff', age:50}
{name:'jeff', age:40}
某些文档将“名称”字段设置为相同的值(2个ricks,2个johns和2个jeffs)。如果两个或多个文档的“名称”字段设置为相同的值,我想要只选择年龄最大的文档。像这样:
{name:'rick', age:35}
{name:'john', age:40}
{name:'jeff', age:50}
是否有30岁的瑞克和35岁的瑞克?我选择35岁的瑞克!等等...
但查询怎么样?
答案 0 :(得分:0)
db.collection.aggregate([{$group:{_id:"$name",sal:{$max:"$age"}}}]);
答案 1 :(得分:0)
db.getCollection('Mytest')。aggregate({$ group:{_ id:{“name”:“$ name”},年龄:{$ max:“$ age”}}})
输出:
{
"_id" : {
"name" : "jeff"
},
"age" : 50
}
/* 2 */
{
"_id" : {
"name" : "john"
},
"age" : 40
}
/* 3 */
{
"_id" : {
"name" : "rick"
},
"age" : 35
}