如何在 mongo 聚合查询中创建集合的 objectID 数组并查找该列表中存在的另一个集合中的 ID

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

我需要一个查询来查找用户集合中存在的任何具有 groups._id 的文档,该文档不存在于 groups 集合的 _id 中

用户集合 - 文档

    {
      "_id": ObjectId("65c35a039773c8593fc45ddb"),
      "email": "email",
      "name": "name",
      "groups": [
        {
          "_id": ObjectId("65c1b7716f130b7c4190104a"),
          "name": "testgroup"
        }
      ]
    },
    {
      "_id": ObjectId("65c35a039773c8593fc45ddf"),
      "email": "email",
      "name": "name",
      "groups": [
        {
          "_id": ObjectId("65c1b7716f130b7c4190104b"),
          "name": "testgroup1"
        }
      ]
    },
    {
      "_id": ObjectId("65c35a039773c8593fc45ddc"),
      "email": "email",
      "name": "name",
      "groups": []
    }

小组收藏-文档

{
    "_id" : ObjectId("65c1b7716f130b7c4190104a"),
    "name" : "testgroup",
  
}
{
    "_id" : ObjectId("65c1b7716f130b7c4190104f"),
    "name" : "testgroup2",
  
}

此查询返回匹配的文档,但如何获取不匹配的文档

db.getCollection("users").aggregate([

   { $match: { $expr:{$ne:[0,{ $size: "$groups" }]} } },
   { $lookup: {
      from: "groups",
      localField: "groups._id",
      foreignField: "_id",
      as: "matchingDocuments"   
    }},  
    { $project: {
      existsInCollection2: { $gt: [{ $size: "$matchingDocuments" }, 0] }
    }}
])
mongodb mongodb-query
1个回答
0
投票

一种选择是比较两个数组的大小:

db.users.aggregate([
  {$match: {"groups.0": {$exists: true}}},
  {$lookup: {
      from: "groups",
      localField: "groups._id",
      foreignField: "_id",
      as: "matchingDocuments",
      pipeline: [{$project: {_id: 1}}]
  }},
  {$match: {$expr: {$ne: [{$size: "$groups"}, {$size: "$matchingDocuments"}]}}}
])

查看它在 mongoDB Playground 上的工作原理

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