TamerB
TamerB

Reputation: 1441

Node.js - Mongoose: Search for multiple items in array in documents

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.

Upvotes: 0

Views: 1767

Answers (3)

Pankaj Khairnar
Pankaj Khairnar

Reputation: 11

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()

Upvotes: 0

Steve Holgado
Steve Holgado

Reputation: 12071

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

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

Upvotes: 2

88jayto
88jayto

Reputation: 707

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.

Upvotes: 2

Related Questions