0

How can I (using Node.js and MongoDB through Mongoose) search for an many items in an array in document.

For example, if I have documents like:

{
    _id: 123, field1: 'abc', field2: ['def', 'ghi', 'jkl'],
    _id: 456, filed1: 'abc', filed2: ['jkl', 'ghi', 'def']
}

And the schema is called schema1, how can I perform a search with a query like

{field1: 'abc', field2: ['def', 'jkl']}

and get both documents (all documents whose field1 = 'abc' and field2 contains both 2 items in the array in query)?

I tried using schema1.find() but it only matches the arrays as a whole not their items. So none of these 2 documents would return.

3 Answers 3

2

You can use the $all operator with the following query:

{
    field1: 'abc', 
    field2: {
        $all: ['def', 'jkl']
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Now I know why trying $all didn't work for me before =D . Many thanks @Steve
No problem. Glad I could help.
2

When I ran into this same issue my solution was to do something this:

{field1: 'abc', field2: 'def', field2:'jkl'}

This should return all documents that have at least both 'def' and 'jkl' inside field2 and 'abc' in field1. It does look a bit awkward and there may be a better way to write this query, but it does work and is totally valid.

Comments

0

To fetch results use

You can use $and for join both condition and to search element in array use $in

db.collectionName.find({ $and : [{ "field1" : "abc"}, { "field2" : { $in : [ "def","jkl"]}}]}).pretty()

Comments

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.