3

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))))));

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

4

1 回答 1

2

我认为这种情况下最简洁、最优雅的查询是您列出的几个组合:

 db.address_book.find({addresses: {$elemMatch: {zip: {$gte:10012, $lte:10040}}}})
于 2012-11-16T04:36:57.990 回答