1

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].

1
  • Demo. $in operator will filter the document that with any value match in the input array. Commented Mar 4, 2022 at 2:31

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! You're right, it does work after all -- I just realized that there was a bug in another part of my code. : P
$in doc link here, if anyone needed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.