Reputation: 281
I'm trying to use $elemMatch
to find an object in an array. I imported the following data into a collection named trails
:
{ "Copper" : [
{"name" : "Spaulding Bowl", "level" : "Extreme Terain", "location" : "East Side"},
{"name" : "Resolution Bowl", "level" : "Double Black", "location" : "East Side"},
{"name" : "Black Bear Glade", "level" : "Double Black", "location" : "East Side"},
{"name" : "Free Fall Glade", "level" : "Double Black", "location" : "East Side"}
]
}
I'm using the syntax from the MongoDB documentation to make the following query:
db.trails.find( { "Copper": { $elemMatch: { "name" : "Spaulding Bowl" } } } )
I have also tried formating it without quotations around the keys:
db.trails.find( { Copper: { $elemMatch: { name : "Spaulding Bowl" } } } )
Instead of returning just one matching element, both return the entire array of objects. Is there a syntax error I'm missing? All tips are appreciated.
Upvotes: 1
Views: 337
Reputation: 76004
$elemmatch(query) returns all rows in a array when there is atleast one row matching the query criteria.
$elemMatch(projection) returns only the first row of all the matching rows when used as projection.
You don't need elemMatch for your case as it is only single criteria.
db.trails.find({"Copper.name": { "Spaulding Bowl" } })
Try as below which uses the elemMatch projection variation.
db.trails.find({}, {"Copper": { $elemMatch: { "name" : "Spaulding Bowl" } } } )
Upvotes: 2