Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo aggregation Match multiple values

I have following documents

  {
       name: 'John',
       Address :'street 1 '
   },
   {
       name: 'Jane',
       Address :'street 2 '
   },
   {
       name: 'Smith',
       Address :'street 3 '
   }

I want to search the multiple document with different vales in mongo aggregation pipeline.

That means name =('John','Smith'). I'm expecting result is

{
   name: 'John',
   Address :'street 1 '
},
{
   name: 'Smith',
   Address :'street 3 '
}

My code is

db.articles.aggregate($match: { $or: [{ name: 'John' }, { name: 'Smith' }]);

This is giving an empty value.is it possible to get document like this way?

like image 868
avancho marchos Avatar asked Mar 09 '20 20:03

avancho marchos


1 Answers

You need to use operator the $in

The $in operator selects the documents where the value of a field equals any value in the specified array.

[{
    $match: {
        name: {
            $in: ['John', 'Smith']
        }
    }
}]

Reference: MongoDB Docs: $in

like image 126
Julio Peña Avatar answered Sep 24 '22 21:09

Julio Peña