How to execute this request in the Mongo and Mongoid console?

I am trying to learn how to query Mongo in more advanced ways. Say my data structure is this:

{ "_id" : "-bcktick-ajman-ae-292932", "asciiname" : "`Ajman", "alternatenames" : [ { "isolanguage" : "no", "alternateNameId" : 2698358, "alternateName" : "Ajman" }, { "isolanguage" : "en", "alternateNameId" : 2698357, "alternateName" : "Ajman" } ] } 

So, finding Ajman easy:

 db.cities.find({ "asciiname":"`Ajman" }) 

However, I want to find cities that only have isolanguage ru . You will notice that isolanguage is in an array of alternate names .

But I can not find the correct syntax in either the client or mongoid

It would be very helpful to rate one (or both).

thanks

+4
source share
1 answer

I think you are looking for the $elemMatch :

 db.cities.find( { 'alternatenames' : { $elemMatch: { isolanguage: 'en'} } }) 

Mongoid does not currently have a helper for $elemMatch , so you need to pass the raw request:

 City.where({ :alternatenames => { '$elemMatch' => { :isolanguage => 'en' } } }) 

More details here at $elemMatch here:

Additional Mongoid support information for $elemMatch here:

+5
source

Source: https://habr.com/ru/post/1345964/


All Articles