如何从多个Mongodb文档的字段数据中获取某个字段的交集数据。想要一个 Mongo 聚合查询,我可以将其添加到我的查询中

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

我已经在使用 Mongo db 聚合查询来获取输出数组。 email 将是查询中输入的电子邮件数组。

**aggregateQuery** = [
{
    '$match': {
        'email': {
            '$in':

                ['[email protected]', '[email protected]', '[email protected]']
        },
        'deleted': false
    }
},
{< Some more logics here >},

    { '$project': { 'email': 1, 'refId': '$dataArray._id' } }
];


**Output**: [
    {
        _id: 't1',
        email: '[email protected]',
        refId: ['ref1', 'ref2', 'ref3','ref4','ref5']
    },
    {
        _id: 't2',
        email: '[email protected]',
        refId: ['ref1', 'ref2','ref5',ref'82']
    },
    {
        _id: 't3',
        email: '[email protected]',
        refId: ['ref2', 'ref5','ref77']
    }
]

所以现在我想更新我的查询,以便它给出 common(或交集) refids 作为输出,记住输入(或输出)不限于 3。

**Expected Output** : [
Common_RefIds:['ref2', 'ref5']
]
arrays mongodb mongodb-query intersection set-intersection
1个回答
0
投票

您需要将所有 refId 数组组合成一个数组数组,然后使用 $setIntersection 减少数组以仅保留公共元素。

管道示例:

[
  {"$match": {
      "email": {"$in": [
          "[email protected]",
          "[email protected]",
          "[email protected]"
      ]},
      "deleted": false
  }},
  {$group: {
      _id: null,
      refId_arrays: {$push: "$refId"},
      first_array: {$first: "$refId"}
  }},
  {$project: {
      common_refId: {$reduce: {
          input: "$refId_arrays",
          initialValue: "$first_array",
          in: {$setIntersection: ["$$this","$$value"]}
      }}
  }}
]

游乐场

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