mongodb 查找具有相同键值但不知道值是什么的文档
mongodb find documents with the same value for a key but do not know what the value is
我在 collection;
中有以下文档
{'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
with po_no
and then filter out the documents where count is less then 1 using $match
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
}
]
可以用$group and then check amount
$size大于1
:
db.col.aggregate([
{
$group: {
_id: "$po_no",
amount: { $push: "$amount" }
}
},
{
$match: {
$expr: {
$gt: [ { $size: "$amount" }, 1 ]
}
}
},
{
$unwind: "$amount"
},
{
$project: {
_id: 0,
po_no: "$_id",
amount: 1
}
}
])
我在 collection;
中有以下文档{'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
with po_no
and then filter out the documents where count is less then 1 using $match
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
}
]
可以用$group and then check amount
$size大于1
:
db.col.aggregate([
{
$group: {
_id: "$po_no",
amount: { $push: "$amount" }
}
},
{
$match: {
$expr: {
$gt: [ { $size: "$amount" }, 1 ]
}
}
},
{
$unwind: "$amount"
},
{
$project: {
_id: 0,
po_no: "$_id",
amount: 1
}
}
])