I'm trying to learn how to query Mongo in more advanced ways. Let's say my data structure is this:
{ "_id" : "-bcktick-ajman-ae-292932", "asciiname" : "`Ajman",
"alternatenames" : [
{
"isolanguage" : "no",
"alternateNameId" : 开发者_StackOverflow2698358,
"alternateName" : "Ajman"
},
{
"isolanguage" : "en",
"alternateNameId" : 2698357,
"alternateName" : "Ajman"
}
]
}
So to find Ajman
is easy:
db.cities.find({ "asciiname":"`Ajman" })
However, I want to find cities that only have an isolanguage
of en. You'll notice the isolanguage
is in the alternatenames array.
But I can't seem to find the correct syntax in either the client or mongoid
Either one (or both) would be greatly appreciated.
Thanks
I think you are looking for the $elemMatch
keyword:
db.cities.find(
{ 'alternatenames' : {
$elemMatch: { isolanguage: 'en'}
}
})
Currently, Mongoid does not have a helper for $elemMatch
so you have to pass in the raw query:
City.where({ :alternatenames => { '$elemMatch' => { :isolanguage => 'en' } } })
More info here on $elemMatch
here:
- http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24elemMatch
- http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29
More info on Mongoid support for $elemMatch
here:
- http://groups.google.com/group/mongoid/browse_thread/thread/8648b451e3957e12
- https://github.com/mongoid/mongoid/issues/750
精彩评论