如何在python中为db.collection.group()编写mongodb查询

时间:2015-03-13 18:18:54

标签: python mongodb mongodb-query pymongo

我正在处理MongoDB查询

db.BH.group({
"key": {
    "AccountId": true,
},
"initial": {
    "count": 0
},
"reduce": function(obj, prev) {
    if (true != null) if (true instanceof Array) prev.count += true.length;
    else prev.count++;
},
"cond":     
    {"$or":[{"Url":{"$regex":"(google)"}},{"Url":{"$regex":"(facebook)"}}]} 
}); 

查询在MongoDB Shell(Robomongo)中运行良好。

我为python编写了相同的查询。

db.BH.group({
"key": {
    "AccountId": True,
},
"initial": {
    "count": 0
},
"reduce": "function(obj, prev) {"
    "if (true != null) if (true instanceof Array) prev.count += true.length;"
    "else prev.count++;"
"}",
"cond": {"$or":[{"Url":{"$regex":"(google)"}},{"Url":{"$regex":"(facebook)"}}]} 
}) 

但是查询会出现错误。

TypeError: group() takes at least 5 arguments (2 given)

我尝试通过以下网站(URL)中给出的方法解决错误

http://blog.pythonisito.com/2012/05/aggregation-in-mongodb-part-1.html

但同样的错误仍然存​​在。

2 个答案:

答案 0 :(得分:1)

group的语法在PyMongo中有所不同。 Javascript中参数对象中的每个键keyinitial等都是Python中的关键字参数:

db.BH.group(key = , initial = , reduce = , cond = )

答案 1 :(得分:0)

group(key, condition, initial, reduce, finalize=None, **kwargs)

您缺少组操作的最后一个参数“finalize”。使用finalize = None应该可以解决问题。

db.BH.group({
    {
        "AccountId": True,
    },
    {"$or":[{"Url":{"$regex":"(google)"}},{"Url":{"$regex":"(facebook)"}}]}, 
    {
        "count": 0
    },
    "function(obj, prev) {"
        "if (true != null) if (true instanceof Array) prev.count += true.length;"
        "else prev.count++;"
    "}",
    None
})