Home > Back-end >  MongoDB query $in operator by multiple keys of object in an array?
MongoDB query $in operator by multiple keys of object in an array?

Time:01-15

I'm trying to $match query in MongoDB by using $in operator as follows :-

The documents in the collection should have similar data like bellow :-

[
  {
    "test": "test01",
    "output": 0
  },
  {
    "test": "test02",
    "output": 5
  },
  {
    "test": "test03",
    "output": 1
  }
]

I tried using this aggregation by doing the following :-

await SampleCollection.aggregate(
  [
    {
      $match: {
        // here it should look for test and output key
        test_and_output: { $in: [{ test: 'test01', output: 0 }, { test: 'test03', output: 1 }] },
      },
    },
  ],
  async function (err, data) {
    if (err) return reject(err);
    if (!data || !data.length) return resolve(null);
    if (data.length) return resolve(data);
  }
);

As you can see above I'm trying to use $in operator to look for 2 keys which is (test, output), any idea how ?

NOTE:- it should meet the 2 conditions at the same time, the 2 keys must equal the object in $in operator so $or operator doesn't work I think.

CodePudding user response:

The provided match stage is looking for documents which contain a field named test_and_output, since none of the sample documents have such a field, nothing matches.

If you need to match several criteria together, use a top-level $or with an array of filters, like:

{$match:{
   $or: [
         { test: 'test01', output: 0 }, 
         { test: 'test03', output: 1 }
        ]
}}

Playground

If that sample data is an array from a single document like:

{
   test_and_order: [
     {
       "test": "test01",
       "output": 0
     },
     {
       "test": "test02",
       "output": 5
     },
     {
       "test": "test03",
       "output": 1
     }
  ]
}

You could use $elemMatch like:

$match: {
    test_and_output: {$elemMatch: {
        $or: [
          {test: "test01", output: 0},
          {test: "test03", output: 1}
        ]
    }}
}

Playground

  • Related