129

If I have a record like this;

{
  "text": "text goes here",
  "words": ["text", "goes", "here"]
}

How can I match multiple words from it in MongoDB? When matching a single word I can do this;

db.find({ words: "text" })

But when I try this for multiple words, it doesn't work;

db.find({ words: ["text", "here"] })

I'm guessing that by using an array, it tries to match the entire array against the one in the record, rather than matching the individual contents.

1 Answer 1

243

Depends on whether you're trying to find documents where words contains both elements (text and here) using $all:

db.things.find({ words: { $all: ["text", "here"] }});

or either of them (text or here) using $in:

db.things.find({ words: { $in: ["text", "here"] }});
Sign up to request clarification or add additional context in comments.

5 Comments

This helped me too, I needed it to find an object ID in an array, and where something like $in: [ ObjectId("4f9f2c336b810d0cf0000017") ] failed, $in: [ "4f9f2c336b810d0cf0000017" ] worked
Is this better than looping the array and performing single find()?
@RohitNair, It's clear to read as well as faster when doc size is big.
db.things.find({ words: { $elemMatch: { $in: ["text","here"] }})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.