如何(轻松)从文档数组中查询字段的一系列值

时间:2012-11-16 03:43:00

标签: mongodb

Windows 7 64 SP1 MongoDB 2.2.0

鉴于此数据:

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} ] } )

我想要所有文件,其中任何邮政编码都在10012-10040范围内。换句话说,我想:

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

此查询返回所需的结果:

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

问题:这是获得结果的最短(最优雅)查询吗?

每个查询:

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} } ] }  )

返回:

{ "_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 } ] }

如果第一种方法最短,则会产生复杂的C ++查询:

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

我认为这是一个常见的查询我错了吗?

1 个答案:

答案 0 :(得分:2)

我认为这个案例中最干净,最优雅的查询是你列出的几个人的组合:

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