【问题标题】:mongodb find documents with the same value for a key but do not know what the value ismongodb查找具有相同键值但不知道值是什么的文档
【发布时间】:2019-03-22 12:32:11
【问题描述】:

我的集合中有以下文档;

{'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'值相同的文档,但不知道哪个值是key;所以会找到以下结果;

{'po_no': '456', 'amount': 0.1}
{'po_no': '456', 'amount': 0.4} 

【问题讨论】:

    标签: mongodb aggregation-framework mongo-shell


    【解决方案1】:

    您可以使用$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 过滤掉计数小于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
        }
      ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-03
        • 1970-01-01
        • 2013-11-26
        • 2015-02-13
        • 2022-01-04
        • 1970-01-01
        • 2012-10-27
        • 2015-08-29
        相关资源
        最近更新 更多