Mongodb文件遍历

时间:2014-12-23 19:45:23

标签: python mongodb mongoengine

我在mongo db中有一个查询,尝试了很多解决方案,但仍然没有找到它工作。任何帮助将不胜感激。

如何在文档中找到名为“channel”的所有键?

  

db.clients.find({“_ id”:69})

{
    "_id" : 69,
    "configs" : {
        "GOOGLE" : {
            "drid" : "1246ABCD",
            "adproviders" : {
                "adult" : [ 
                    {
                        "type" : "landing",
                        "adprovider" : "abc123",
                        "channel" : "abc456"
                    }, 
                    {
                        "type" : "search",
                        "adprovider" : "xyz123",
                        "channel" : "xyz456"
                    }
                ],
                "nonadult" : [ 
                    {
                        "type" : "landing",
                        "adprovider" : "pqr123",
                        "channel" : "pqr456"
                    }, 
                    {
                        "type" : "search",
                        "adprovider" : "lmn123",
                        "channel" : "lmn456"
                    }
                ]
            }
        },
        "channel" : "ABC786",
        "_cls" : "ClientGoogleDoc"
    }
}

尝试查找名称为频道的密钥

  

db.clients.find({“_ id”:69,“channel”:true})

期待:

{"channels": ["abc456", "xyz456", "ABC786", "xyz456", "pqr456", "lmn456", ...]}

2 个答案:

答案 0 :(得分:1)

据我所知,您必须自己使用python递归遍历字典才能构建上面所需的列表:

channels = []

def traverse(my_dict):
    for key, value in my_dict.items():
        if isinstance(value, dict):
            traverse(value)
        else:
            if key == "channel":
                channels.append(value)

traverse({"a":{"channel":"abc123"}, "channel":"xyzzz"})  
print(channels)

输出:

['abc123', 'xyzzz']

然而,使用名为projections的东西,你可以得到你想要的东西(但不是真的,因为你必须手动指定所有的频道):

db.clients.find({"_id": 69}, {"configs.channel":1})

返回:

{ "_id" : ObjectId("69"), "configs" : { "channel" : "ABC786" } }

如果你想变得非常花哨,你可以写一个generator函数来生成给定字典中的所有键,无论多深:

my_dict = { "a": {
                "channel":"abc123",
                "key2": "jjj",
                "subdict": {"deep_key": 5, "channel": "nested"}
            }, 
            "channel":"xyzzz"}

def getAllKeys(my_dict):
    for key, value in my_dict.items():
        yield key, value
        if isinstance(value, dict):
            for key, value in getAllKeys(value):
                yield key, value

for key, value in getAllKeys(my_dict):
    if key == "channel":
        print value

输出:

nested
abc123
xyzzz

答案 1 :(得分:0)

您可以使用$project mongodb运算符仅获取特定键的值。查看http://docs.mongodb.org/manual/reference/operator/aggregation/project/

上的文档