【问题标题】:how to write mongodb query in python for db.collection.group()如何在 python 中为 db.collection.group() 编写 mongodb 查询
【发布时间】:2017-06-06 01:35:39
【问题描述】:

我正在处理一个 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

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

【问题讨论】:

    标签: python mongodb mongodb-query pymongo


    【解决方案1】:

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

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

    【讨论】:

    • 我更正了语法,但仍然收到错误 TypeError: group() 需要至少 5 个参数(给定 4 个) @wdberkeley
    【解决方案2】:
    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
    })
    

    【讨论】:

      猜你喜欢
      • 2019-08-19
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多