无法运行MongoDB聚合命令(OperationFailure)



我试图在python中使用MongoDB聚合管道命令(使用PyMongo(,但遇到了以下错误:

pymongo.errors.OperationFailure: {aggregate: 1} is not valid for '$match'; a collection is required., full error: {'ok': 0.0, 'errmsg': "{aggregate: 1} is not valid for '$match'; a collection is required.", 'code': 73, 'codeName': 'InvalidNamespace'}

我尝试删除第一个匹配项,但它只会将"$match"更改为"$project"。这是我正在使用的管道:

[
{
"$match": {"$text": {"$search": "{self.keyword}"}}
},
{
"$project":
{
"wholeDate": {"$dateFromString": {"dateString": "$date"}},
"year": {"$year": {"$dateFromString": {"dateString": "$date"}}},
}
},
{
"$match": {"wholeDate": {"$gte": "{self.date_from_}", "$lte": "{self.date_until_}"}}
},
{
"$group":
{
"_id": {"year": "$year"},
"count": {"$sum": 1}
}
}
]

当我直接在MongoDB上运行相同的管道时,它工作得很好。工作时,它应该给出以下输出:

{ "_id" : { "year" : 2018 }, "count" : 34 }

在指定的数据库上运行聚合函数时,我认为不需要通过给出参数来再次指定集合。我在这里找到的(https://docs.mongodb.com/manual/reference/command/aggregate/#command-字段(,因此我将函数调用更改为:

mongo.test.aggregate(aggregate="test", pipeline=self.pipeline)

现在效果很好。有些文档从未提及集合参数。

最新更新