1

I need to check all the documents whose specific field is contained in an array.

For example I have the array

arr = ['a', 'b', 'a']

I want to match all the documents that has field my_letter equal to a or b.

I have the documents:

[
  {
    _id: ObjectID(),
    my_letter:'d'
  },
  {
    _id: ObjectID(),
    my_letter:'a'
  },
  {
    _id: ObjectID(),
    my_letter:'b'
  }
]

I want the aggregation to return

[
  {
    _id: ObjectID(),
    my_letter:'a'
  },
  {
    _id: ObjectID(),
    my_letter:'b'
  }
]

I tried this in my $match pipeline

{
  $match: {
    _id: {
      $elemMatch: {
        $or: [
          { $eq: ["a"] },
          { $eq: ["b"] },
        ],
      },
    },
  },
},

Of course it doesn't work. How would You suggest to complete the $match pipeline?

4
  • 3
    Hey, please edit your question and be more specific? I'm very confused by your question. "I need to check all the documents whose specific field is contained in an array." or "I want to match all the documents that has field my_letter equal to a or b." Which one you want? Do you want to query the my_letter field or the _id field? Please provide full examples of documents you have in the database and the result you want to achieve. Commented Mar 17, 2022 at 23:42
  • The real documents are too big, but basically I need to get all the users that has their _id in a given array. I tried with generic examples. Thank you btw Commented Mar 18, 2022 at 7:56
  • And what my_letter has to do with the _id? if the accepted answer is the correct one you are not even using _id filter Commented Mar 18, 2022 at 16:13
  • @LucasSoares It is just an example that can be applied doesn't matter the exact name. I just don't want to put myDB model here. The attribute name is not important. If it's foo or _id or my_letter is the same thing to me. Just wanted to abstract it. Sorry if I was unclear Commented Mar 19, 2022 at 10:34

1 Answer 1

6
db.collection.find({
  my_letter: {
    $in: [ "a", "b" ]
  }
})

mongoplayground


db.collection.aggregate([
  {
    $match: {
      my_letter: {
        $in: [ "a", "b" ]
      }
    }
  }
])

mongoplayground

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.