简体   繁体   English

Mongodb 使用输入数组聚合

[英]Mongodb aggregate by using input array

I am struggling to create an aggregate query for my MongoDB database.我正在努力为我的 MongoDB 数据库创建聚合查询。

here is my input array这是我的输入数组

recipients = [1,2,7]

here is my database collection这是我的数据库集合

{
    "chapter": 1,
    "targets": [
      {
        type: 'user',
        recipient: 1
      }
    ]
  },
  {
    "chapter": 1,
    "targets": [
      {
        type: 'user',
        recipient: 2
      }
    ]
  },
  {
    "chapter": 2,
    "targets": [
      {
        type: 'user',
        recipient: 3
      }
    ]
  },
  {
    "chapter": 3,
    "targets": [
      {
        type: 'user',
        recipient: 4
      }
    ]
  },

the desired output所需的输出

should be [] because 7 doesn't exist in targets.recipient in the collection

here is what I've tried so far这是我迄今为止尝试过的

db.collection.aggregate([
  {
      $match: {
        'targets.recipient': { $in: recipients },
      },
    }
])

Any suggestions, thank you.任何建议,谢谢。

The way $in works is that it returns the document if there's any match between it's value and the array you're passing as a parameter.$in 的工作方式是,如果它的值与您作为参数传递的数组之间存在任何匹配,则它返回文档。 It looks like in your case you can use $in for initial filtering but then you want to return the result only if the result set contains all the values from the input array.在您的情况下,您似乎可以使用$in进行初始过滤,但是只有当结果集包含输入数组中的所有值时,您才希望返回结果。 In order to achieve it you can use $group to get all matching results and then apply $all :为了实现它,您可以使用$group获取所有匹配结果,然后应用$all

db.collection.aggregate([
    {
        $match: { "targets.recipient": { $in: [1,2,7] } }
    },
    {
        $group: {
            _id: null,
            docs: { $push: "$$ROOT" }
        }
    },
    {
        $match: { "docs.targets.recipient": { $all: [1,2,7] } }
    }
])

Mongo Playground蒙戈游乐场

// only matched documents will be shown.
> db.targets.aggregate([ {$match:{"targets.recipient":{$in:[1,2,7]}}}, {$project:{chapter:1,targets:1}} ]).pretty();
{
        "_id" : ObjectId("5f5de14c598d922a1e6eff4d"),
        "chapter" : 1,
        "targets" : [
                {
                        "type" : "user",
                        "recipient" : 1
                }
        ]
}
{
        "_id" : ObjectId("5f5de14c598d922a1e6eff4e"),
        "chapter" : 1,
        "targets" : [
                {
                        "type" : "user",
                        "recipient" : 2
                }
        ]
}
>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM