我在一个集合中有以下文档;
{'po_no': '456', 'amount': 0.1}
{'po_no': '455', 'amount': 0.2}
{'po_no': '454', 'amount': 0.3}
{'po_no': '456', 'amount': 0.4}
我喜欢找到'po_no'具有相同值的文档,但不知道该键的值是什么;所以会发现以下结果;
{'po_no': '456', 'amount': 0.1}
{'po_no': '456', 'amount': 0.4}
您可以将$group
与po_no
一起使用,然后使用$match
过滤出count小于1的文档
db.collection.aggregate([
{ "$group": {
"_id": "$po_no",
"count": { "$sum": 1 },
"amount": { "$push": "$amount" }
}},
{ "$match": { "count": { "$gt": 1 }}},
{ "$unwind": "$amount" },
{ "$project" : { "count": 0 }}
])
产量
[
{
"_id": "456",
"amount": 0.1
},
{
"_id": "456",
"amount": 0.4
}
]