我有一个数据库,里面有这个信息:
{"_id":1, "test":6,"foo":[{"mom":5,"dad":10},{"mom":7, "dad":12}]}
{"_id":2, "test":9,"foo":[{"mom":6,"dad":20},{"mom":7, "dad":15}]}
{"_id":3, "test":10, "foo":[{"mom":10,"dad":13},{"mom":2, "dad":19}]}我在mongo中用mom=7从数据库中查询:
cursor = foo.find({"foo.mom":7},{"foo.$":1,"_id":0, "test":1})
for key in cursor:
print key它会打印出以下内容:
{"test":6,"foo":[{"mom":7, "dad":12}]}
{"test":9,"foo":[{"mom":7, "dad":15}]}如果我使用
print key['test']我只会得到"test“的结果
所以,问题是:我如何才能得到这样的结果:
{"test":6,"foo":[{"dad":12}]}
{"test":9,"foo":[{"dad":15}]}我试着用
print key["foo.dad"]但是它只返回一个错误
发布于 2013-04-17 13:22:16
由于"foo“的值保存在一个数组中,因此您需要使用键”foo“”dad“从结果中打印”dad“的值。
我使用的代码是这样的:
cursor = foo.find({"foo.mom":7},{"foo.$":1,"_id":0, "test":1})
for key in cursor:
print key
print key['test']
print key['foo'][0]['dad']得到的结果是这样的:
{u'test': 6.0, u'foo': [{u'dad': 12.0, u'mom': 7.0}]}
6.0
12.0
{u'test': 9.0, u'foo': [{u'dad': 15.0, u'mom': 7.0}]}
9.0
15.0如果你想得到不带'mom‘字段的结果:
{"test":6,"foo":[{"dad":12}]}
{"test":9,"foo":[{"dad":15}]}您可以使用聚合框架:
db.foo.aggregate([
{ $unwind : "$foo" },
{ $match : { "foo.mom" : 7 }},
{ $project : {
_id : 0,
test : 1,
"foo.dad" : "$foo.dad"
}},
])结果是:
{
"result" : [
{
"test" : 6,
"foo" : {
"dad" : 12
}
},
{
"test" : 9,
"foo" : {
"dad" : 15
}
}
],
"ok" : 1
}https://stackoverflow.com/questions/16050865
复制相似问题