Vishal Gupta
Vishal Gupta

Reputation: 23

How to get intersection data of a field from multiple Mongodb document's field's data. Want a Mongo aggregate Query which I can add in my query

I am already using a Mongo db Aggregate Query to get a array of output. email will be the array of emails as input in the query.

**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']
    }
]

So now I want to update my query so that it gives common (or intersection) refids as output keeping in mind input (or output) is not limited to 3.

**Expected Output** : [
Common_RefIds:['ref2', 'ref5']
]

Upvotes: 0

Views: 35

Answers (1)

Joe
Joe

Reputation: 28326

You would need to combine all of the refId arrays into an array of arrays, then reduce over than array using $setIntersection to keep just the common elements.

Example pipeline:

[
  {"$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"]}
      }}
  }}
]

Playground

Upvotes: 0

Related Questions