Reputation: 222
Consider following model in mongoose:
var specie = mongoose.Schema({
order: String,
family: String,
genus: String,
species: String,
properties: [
{property:String,
value:String}
]
});
I am trying to build a query that will return the documents based upon specific values in the properties array.
Below is an example of my query:
var query = {
$and: [
{"properties.property":"number of wings","properties.value":"2"},
{"properties.property":"antenna end","properties.value":"clubbed"}
]
}
I thought this query would work but it actually returns all document that have a property "number of wings" and "antenna end" and a value "4" and value "clubbed".
I want the query to return those documents that have following objects in the properties array:
{property: "number of wings", value: "2"} and
{property: "antenna end", value:"clubbed"}
However the above query also returns the documents who have following property:
{property: "number of legs", value:"2"}
How can I resolve this?
Upvotes: 0
Views: 192
Reputation: 222
I believe I found my own answer. I have to use $elemMatch in the query:
var query = {
$and: [
{properties: {$elemMatch: {property:"number of wings",value:"2"}}},
{properties: {$elemMatch: {"property":"antenna end","value":"clubbed"}}}
]
}
Adding the resource link: http://docs.mongodb.org/manual/reference/operator/query/elemMatch/#array-of-embedded-documents
This seems to return the correct results.
Upvotes: 1