mongodb查找具有相同值的文档但不知道该值是什么

问题描述 投票:2回答:2

我在一个集合中有以下文档;

{'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} 
mongodb aggregation-framework mongo-shell
2个回答
2
投票

你可以使用$group,然后检查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
        }
    }
])

MongoDB playground


2
投票

您可以将$grouppo_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
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.