Reputation: 1441
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
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
Reputation: 12071
You can use the $all operator with the following query:
{
field1: 'abc',
field2: {
$all: ['def', 'jkl']
}
}
Upvotes: 2
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