【问题标题】:Pymongo dict element in array output数组输出中的 Pymongo dict 元素
【发布时间】:2013-04-17 13:22:16
【问题描述】:

我有一个包含此信息的数据库:

{"_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 从 db 查询:

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":6,"foo":[{"dad":12}]}
{"test":9,"foo":[{"dad":15}]}

我尝试使用

print key["foo.dad"]

但它只返回一个错误

【问题讨论】:

    标签: python mongodb python-2.7 pymongo bottle


    【解决方案1】:

    由于“foo”的值保存在数组中,因此需要使用 key['foo'][0]['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
    

    如果你想得到没有“妈妈”字段的结果:

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

    【讨论】:

      猜你喜欢
      • 2013-10-04
      • 1970-01-01
      • 2013-08-07
      • 2018-01-28
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      相关资源
      最近更新 更多