Francesca Kukral
Francesca Kukral

Reputation: 49

Querying array field in MongoDB to contain at least one element of an array

Scenario: I have a collection of documents in MongoDB, which have a field called "arrayField" that contains an array of numbers. I have an array of numbers [1, 2, 3], and I want to query this collection to return all documents where the contents of the array field contain at least one (not necessarily all) of the elements of [1, 2, 3]. So for instance, if one of the documents has [1, 6, 7] in arrayField, it would be returned.

How to properly formulate the search options for .find() to perform such a query? I tried {'arrayField': { $in: [1, 2, 3]} }, but that only returns documents where the arrayField has only one element -- just [1] or just [2] or just [3].

Upvotes: 1

Views: 5288

Answers (1)

Anuj Panchal
Anuj Panchal

Reputation: 415

I think the following query will help you

db.collection.find({
  "arrayField": {
    "$in": [1, 2, 3]
  }
})

This will return all those documents that have either of 1, 2 or 3 in the value of arrayField field in your document.

Upvotes: 2

Related Questions