Home > OS >  How to match an element in array? MongoDB aggregation
How to match an element in array? MongoDB aggregation

Time:03-18

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: [new ObjectID(chatWith as string)] },
          { $eq: [new ObjectID(userId as string)] },
        ],
      },
    },
  },
},

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

CodePudding user response:

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

mongoplayground


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

mongoplayground

  • Related