pymongo中带有forEach函数的Mongo聚合查询不起作用



我有以下mongo聚合查询

db.configurations.aggregate([{$group:{_id:{model:"$model", vendor :"$vendor",access_level : "$access_level",config_data_type :"$config_data_type"}, dups:{$push:"$_id"}, count: {$sum: 1}}},
{$match:{count: {$gt: 1}}}
]).forEach(function(doc){
doc.dups.shift();
db.configurations.remove({_id : {$in: doc.dups}});
});

对于pymongo,我已经写了一个相当于:


pipeline = [{"$group":{"_id":{"model":"$model", "vendor" :"$vendor","access_level" : "$access_level","config_data_type" :"$config_data_type"}, "dups":{"$push":"$_id"}, "count": {"$sum": 1}}},{"$match":{"count": {"$gt": 1}}}]
dest_col.aggregate(pipeline).forEach(bson.Code( '''
function(doc){
doc.dups.shift();
dest_col.remove({"_id ": {"$in": doc.dups}});
}'''));

导致以下错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'CommandCursor' object has no attribute 'forEach'

如果我犯了任何语法错误,请纠正。或者让我知道我是否需要遵循任何其他格式来使其工作

将聚合封装在list中,如下所示-因为聚合函数返回一个cursor对象。另外,以前的解决方案也不起作用,因为pythin没有类似forEach的东西。您必须执行for in才能进行迭代。

result = list(dest_col.aggregate(pipeline))
for doc in result:
bson.Code( '''
function(doc){
doc.dups.shift();
dest_col.remove({"_id ": {"$in": doc.dups}});
}''')
I am not python developer. Plz chk the code for syntax errors.

最新更新