2

I am working on a MongoDB query

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)"}}]} 
}); 

The query is working fine in MongoDB Shell(Robomongo).

I have written the same query for 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)"}}]} 
}) 

But error is coming for the query.

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

I tried to solve the error from the method given in the below website(URL)

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

But the same error persists.

ekad
  • 14,436
  • 26
  • 44
  • 46
abhyuday
  • 126
  • 1
  • 9

2 Answers2

1

The syntax of group is different in PyMongo. Each of the keys key, initial, etc. in the argument object in Javascript is a keyword argument in Python:

db.BH.group(key = , initial = , reduce = , cond = )
wdberkeley
  • 11,531
  • 1
  • 28
  • 23
  • I corrected the syntax but still getting the error **TypeError: group() takes at least 5 arguments (4 given)** @wdberkeley – abhyuday Mar 16 '15 at 19:20
0
group(key, condition, initial, reduce, finalize=None, **kwargs)

You are missing the last parameter "finalize" for the group operation. Using finalize=None should solve the problem.

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
})
thegreenogre
  • 1,559
  • 11
  • 22