0

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.

2
  • Please provide sample documents and the expected results from them Commented Jan 14, 2023 at 12:06
  • $or is exactly what you need I think. Remove test_and_output: and one pair of the curly brackets, then swap $in with $or and I think you have it Commented Jan 14, 2023 at 14:11

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.