Invalid operator '$size' in aggregation

烈酒焚心 提交于 2019-12-31 05:28:13

问题


I got the following piece of code:

from pymongo import MongoClient
client = MongoClient('ipOfServer')
db = client.admin
db.authenticate('login', 'password',
source='admin_')
heh = list(db.events.aggregate(
    [
        {"$match": {"status": 'start'}},
        {"$group": {"_id": "$eventName", "players": {"$addToSet": "$uid"}}},
        {"$project": {"_id": 1, "Count": {"$size": "$players"}}}
    ]))
print(heh)

and this is worked for the original programmer who wrote and tested it code result while testing. But when I try to run it I'm getting this error:

pymongo.errors.OperationFailure: exception: invalid operator '$size'

I'm using mongo version 2.4.14 and python 2.7.12 with the sublime text editor. Could anyone suggest ways to solve this problem, it would be appreciated.


回答1:


The reason is because the $size array aggregation operator is new in MongoDB 2.6 and you are actually running MongoDB 2.4.

I suggest you upgrade your MongoDB server to at least 3.0. But if for some reason you don't want to upgrade now, you will need to $unwind the "players" array and $group by "_id" then return the count using the $sum accumulator operator.

heh = list(db.events.aggregate(
    [
        {"$match": {"status": 'start'}},
        {"$group": {"_id": "$eventName", "players": {"$addToSet": "$uid"}}},
        {"$unwind": "$players"},
        {"$group": {"_id": "$_id", "Count": {"$sum": 1}}},
    ]))


来源:https://stackoverflow.com/questions/38523546/invalid-operator-size-in-aggregation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!