[英]Mongo aggregate query with forEach function in pymongo not working
我有以下 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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.