【问题标题】:Mongo aggregate query with forEach function in pymongo not workingpymongo中带有forEach函数的Mongo聚合查询不起作用
【发布时间】:2021-02-10 14:26:40
【问题描述】:

我有以下 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'

如果我有任何语法错误,请更正。或者让我知道我是否需要遵循任何其他格式才能使其正常工作

【问题讨论】:

    标签: python mongodb pymongo pymongo-3.x


    【解决方案1】:

    将聚合包裹在 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.
    

    【讨论】:

    • 我得到这个错误 -> AttributeError: 'list' object has no attribute 'forEach'
    • 感谢您的支持。如果对您有用,您能否接受答案。
    猜你喜欢
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多