{
"_id":{
"oid":"4f33bf69873dbc73a7d21dc3"
},
"country":"IND",
"states":[{
"name":"orissa",
"direction":"east",
"population":41947358,
"districts":[{
"name":"puri",
"headquarter":"puri",
"population":1498604
},
{
"name":"khordha",
"headquarter":"bhubaneswar",
"population":1874405
}
]
},
{
"name":"andhra pradesh",
"direction":"south",
"population":84665533,
"districts":[{
"name":"rangareddi",
"headquarter":"hyderabad",
"population":3506670
},
{
"name":"vishakhapatnam",
"headquarter":"vishakhapatnam",
"population":3789823
}
]
}
]
}
在上面的集合(即国家/地区)中,我只有一个文档,我想获取有关特定状态的详细信息(比如说“country.states.name”:“orissa”),但我希望我的结果在这里而不是整个文件。在Mogo有一条路......
{
"name": "orissa",
"direction": "east",
"population": 41947358,
"districts": [
{
"name": "puri",
"headquarter": "puri",
"population": 1498604
},
{
"name": "khordha",
"headquarter": "bhubaneswar",
"population": 1874405
}
]
}
由于
答案 0 :(得分:7)
试过这个:
db.countries.aggregate(
{
"$project": {
"state": "$states",
"_id": 0
}
},
{
"$unwind": "$state"
},
{
"$group": {
"_id": "$state.name",
"state": {
"$first": "$state"
}
}
},
{
"$match": {
"_id": "orissa"
}
}
);
得到了:
{
"result" : [
{
"_id" : "orissa",
"state" : {
"name" : "orissa",
"direction" : "east",
"population" : 41947358,
"districts" : [
{
"name" : "puri",
"headquarter" : "puri",
"population" : 1498604
},
{
"name" : "khordha",
"headquarter" : "bhubaneswar",
"population" : 1874405
}
]
}
}
],
"ok" : 1
答案 1 :(得分:5)
你现在不能这样做,但你可以在aggregation framework中以$放松。您现在可以尝试使用实验2.1分支,稳定版本将在2.2中出现,可能会在几个月内出现。
答案 2 :(得分:2)
mongodb中的任何查询都会返回根文档。
如果您知道嵌套数组中的序数状态,则只有一种方法可以通过$slice加载父文档:
// skip ordinalNumberOfState -1, limit 1
db.countries.find({_id: 1}, {states:{$slice: [ordinalNumber -1 , 1]}})
$ slice按默认顺序工作(因为文档已插入嵌套数组中)。 此外,如果您不需要来自某个国家/地区的字段,则只能在结果中包含_id和状态:
db.countries.find({_id: 1}, {states:{$slice: [ordinalNumber -1 , 1]}, _id: 1})
然后结果文档将如下所示:
{
"_id":{
"oid":"4f33bf69873dbc73a7d21dc3"
},
"states":[{
"name":"orissa",
"direction":"east",
"population":41947358,
"districts":[{
"name":"puri",
"headquarter":"puri",
"population":1498604
},
{
"name":"khordha",
"headquarter":"bhubaneswar",
"population":1874405
}
]
}]
}
答案 3 :(得分:1)
db.countries.find({ "states": { "$elemMatch": { "name": orissa }}},{"country" : 1, "states.$": 1 })
答案 4 :(得分:0)
如果您不想使用aggregate
,可以使用下划线(默认包含)在应用程序层轻松完成:
var country = Groops.findOne({"property":value);
var state _.where(country, {"state":statename});
这将为您提供与statename
匹配的完整状态记录。非常方便。