MongoDB嵌套查询

最近刚接触mongodb,需要取出一个嵌套文档中的值,网上查询的各种解决方案都是需要解析json,mongodb官网文档也没找到哪里有说明。

经过尝试,发现可以如下查询
collection数据如下:

{ "_id" : ObjectId("5880b72ce4b02c3ae10549b8"), "segments" : { "HKGBKK" : { "airline" : "HX", "cabinCodeMap" : {  } } }, "timestamp" : NumberLong("1484830508116") }
{ "_id" : ObjectId("5880b72ce4b02c3ae10549b9"), "segments" : { "HKGBKK" : { "airline" : "HX", "cabinCodeMap" : {  } } }, "timestamp" : NumberLong("1484830508117") }
{ "_id" : ObjectId("58818b8de4b02c3ae10549ba"), "segments" : { "CANSEL" : { "airline" : "CZ", "timestamp" : NumberLong("1484884877858") }

需要取出segments中HKGBKK下的airline的vaule为HX的记录,执行如下:

> db.collection.find({'segments.HKGBKK.airline':'HX'}).limit(2)
{ "_id" : ObjectId("5880b72ce4b02c3ae10549b8"), "segments" : { "HKGBKK" : { "airline" : "HX", "cabinCodeMap" : {  } } }, "timestamp" : NumberLong("1484830508116") }
{ "_id" : ObjectId("5880b72ce4b02c3ae10549b9"), "segments" : { "HKGBKK" : { "airline" : "HX", "cabinCodeMap" : {  } } }, "timestamp" : NumberLong("1484830508117") }

既然可以通过嵌套查询出记录,那么类似的,应该也可以修改嵌套数据,由于查询的是业务数据库,此处不提供具体例子,后续自己测试时有结果再补充:)

你可能感兴趣的:(MongoDB嵌套查询)