MongoDB group 使用 $first 获取指定字段

原测试数据:

{ "_id" : ObjectId("59a221054afa291a4e0a974d"), "name" : "jack", "age" : 16, "sex" : "male"}
{ "_id" : ObjectId("59a221144afa291a4e0a974e"), "name" : "lucy", "age" : 16, "sex" : "female"}
{ "_id" : ObjectId("59a221304afa291a4e0a9750"), "name" : "lili", "age" : 18, "sex" : "female" }
{ "_id" : ObjectId("59b0a98bf4eee74a4359353d"), "name" : "jack", "age" : 16, "sex" : "male"}
{ "_id" : ObjectId("59e5c25a483b8642c5ac3ded"), "name" : "jame", "age" : 17, "sex" : "unknown"}

以age 和sex分组。获取age, sex, name字段

 db.a_test.aggregate([{'$group':{_id:{age:"$age",sex:"$sex"}, name:{$first:"$name"}}},{'$project':{_id:false,age:"$_id.age",sex:"$_id.sex", name:"$name"}}]);

获取到的数据

{ "age" : 17, "sex" : "unknown", "name" : "jame" }
{ "age" : 18, "sex" : "female", "name" : "lili" }
{ "age" : 16, "sex" : "female", "name" : "lucy" }
{ "age" : 16, "sex" : "male", "name" : "jack" }

你可能感兴趣的:(MongoDB)