[英]Mongo aggregate query with forEach function in pymongo not working
I have the following mongo aggregate query我有以下 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}});
});
For pymongo i have written a equivalent of it as:对于 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}});
}'''));
It is resulting in the following error:它导致以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'CommandCursor' object has no attribute 'forEach'
Please correct if any syntax error i have done.如果我有任何语法错误,请更正。 or let me know if any other format i need to follow to get it working
或者让我知道是否需要遵循任何其他格式才能使其正常工作
Wrap the aggregate inside list
like below - Because aggregate function returns a cursor
object.将聚合包裹在
list
如下所示 - 因为聚合函数返回一个cursor
对象。 Also previous solution was not working because pythin don't have anything like forEach
.以前的解决方案也不起作用,因为 pythin 没有像
forEach
这样的东西。 You will have to do for in
to iterate.你将不得不
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.