Therefore
Therefore

Reputation: 367

How to (easily) query a range of values of a field from an array of documents

Windows 7 64 SP1 MongoDB 2.2.0

Given this data:

db.address_book.drop()
db.address_book.save({"_id":1, "addresses": [ {"zip": 10018} , {"zip": 10012} ] } )
db.address_book.save({"_id":2, "addresses": [ {"zip": 11216} , {"zip": 10012} ] } )
db.address_book.save({"_id":3, "addresses": [ {"zip": 11215} , {"zip": 10010} ] } )
db.address_book.save({"_id":4, "addresses": [ {"zip": 10011} , {"zip": 10041} ] } )
db.address_book.save({"_id":5, "addresses": [ {"zip": 97202} , {"zip": 97201} ] } )
db.address_book.save({"_id":6, "addresses": [ {"zip": 10038} , {"zip": 97201} ] } )

I want all documents where any of its zip codes are in the range 10012-10040. In other words, I want:

{ "_id" : 1, "addresses" : [ { "zip" : 10018 }, { "zip" : 10012 } ] }
{ "_id" : 2, "addresses" : [ { "zip" : 11216 }, { "zip" : 10012 } ] }
{ "_id" : 6, "addresses" : [ { "zip" : 10038 }, { "zip" : 97201 } ] }

This query returns the desired results:

db.address_book.find( { "addresses": { $elemMatch: { "$and" :[ { "zip": {$gte: 10012} } ,  {"zip": {$lte: 10040} } ] } } } )

Question: Is this the shortest (most elegant) query to get the results?

Each of these queries:

db.address_book.find( { "addresses": { $elemMatch: { "zip": {$gte: 10012} , "zip": {$lte: 10040} } } } )
db.address_book.find( {"addresses.zip" : {$gte:10012, $lte:10040} } )
db.address_book.find( {"$and" :[ { "addresses.zip": {$gte: 10012} } ,  {"addresses.zip": {$lte: 10040} } ] }  )

Return this:

{ "_id" : 1, "addresses" : [ { "zip" : 10018 }, { "zip" : 10012 } ] }
{ "_id" : 2, "addresses" : [ { "zip" : 11216 }, { "zip" : 10012 } ] }
{ "_id" : 3, "addresses" : [ { "zip" : 11215 }, { "zip" : 10010 } ] }
{ "_id" : 4, "addresses" : [ { "zip" : 10011 }, { "zip" : 10041 } ] }
{ "_id" : 6, "addresses" : [ { "zip" : 10038 }, { "zip" : 97201 } ] }

If the first method is the shortest, it makes for a complex C++ query:

mongo::Query selector = QUERY("addresses" << BSON("$elemMatch" <<
   BSON("$and" <<BSON_ARRAY(BSON("zip" << BSON("$gte"<<10012)) <<
                            BSON("zip" << BSON("$lte" << 10040))))));

Am I wrong in thinking that this would be a common query?

Upvotes: 3

Views: 1615

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312129

I think the cleanest, most elegant query for this case is a combination of a couple you listed:

 db.address_book.find({addresses: {$elemMatch: {zip: {$gte:10012, $lte:10040}}}})

Upvotes: 2

Related Questions