dzdmmtf
dzdmmtf

Reputation: 499

mongodb find all documents with a field equal to one of the given array elements

Suppose we have three documents in a collection of mongodb like below:

{ book: "a" }, { book: "b" }, { book: "c" }

I want a query that gives all documents that their book field value is a member of a given array. For example if the given array is ["a", "c", "d"], the query must return the first and the third document as result because "a" and "c" are members of array.

Is there a query for this to do it all at once or the only way is to loop over the given array and use a simple find query?

Upvotes: 1

Views: 1490

Answers (2)

Montgomery Watts
Montgomery Watts

Reputation: 4034

Yes, this is possible by using the $in operator.

In the mongo shell this would look like db.<collectionName>.find({ book: { $in: [ "a", "c", "d" ] }})

Upvotes: 1

Cptmaxon
Cptmaxon

Reputation: 525

see $in operator https://docs.mongodb.com/manual/reference/operator/query/in/

in your case

db.books.find( { book: { $in:["a", "c", "d"]} } )

Upvotes: 4

Related Questions