Appearance
原测试数据:
[
{ "_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" }
]
参考链接https://blog.csdn.net/xiojing825/article/details/78362972