如何在 MongoDB 中使用查找查询查找丢失的 ID

问题描述 投票:0回答:1

我在 MongoDB 中有一个查询,例如:

db.getCollection('customerOrder').find({
  "orderDocument.accountInfo.ban": { 
    $in: ["330650872","330651099","330651125","330651561","330681521"]
  }
})

我正在通过 5 个禁令,但只找到了 3 个禁令,还有 2 个未找到禁令。 我想知道控制台中缺少的禁令。我正在使用 Robo3t 编辑器。

mongodb mongodb-query spring-data-mongodb
1个回答
0
投票

您可以先找到您匹配的结果(即3条记录),将它们分组为一个列表。然后使用 $setDifference 比较您的完整列表以找到 2 个缺失的列表。

db.customerOrder.aggregate([
  {
    $match: {
      "orderDocument.accountInfo.ban": {
        $in: [
          "330650872",
          "330651099",
          "330651125",
          "330651561",
          "330681521"
        ]
      }
    }
  },
  {
    $group: {
      _id: null,
      found: {
        "$addToSet": "$orderDocument.accountInfo.ban"
      }
    }
  },
  {
    "$addFields": {
      fullList: [
        "330650872",
        "330651099",
        "330651125",
        "330651561",
        "330681521"
      ]
    }
  },
  {
    "$addFields": {
      notfound: {
        "$setDifference": [
          "$fullList",
          "$found"
        ]
      }
    }
  }
])

蒙戈游乐场

© www.soinside.com 2019 - 2024. All rights reserved.