首页 > 解决方案 > 在 python (pymongo) 中执行 Mongodb 命令时出错

问题描述

我有以下问题。我有一些 mongodb 代码,可以删除 mongodb 集合中的重复记录。那是有问题的代码:

db.getCollection('News').find({}, { 'TituloPrincipal': 1 }).sort({ _id: 1 }).forEach(function(record) { db.getCollection('News').remove({ _id: { $gt: record._id }, 'TituloPrincipal': record.TituloPrincipal }); });

何时:“ News ”是集合,“ TituloPrincipal ”是要删除的每个文档中的重复记录。

但是,当我在 python 的eval () 函数中运行此代码时,出现以下错误:

   eval(
  File "<string>", line 1
    db.getCollection('News').find({}, { 'TituloPrincipal': 1 }).sort({ _id: 1 }).forEach(function(record){ db.getCollection('News').remove({ _id: { $gt: record._id }, 'TituloPrincipal': record.TituloPrincipal }); });
                                                                                                         ^
SyntaxError: invalid syntax 

我运行的代码是一个函数,它是这样的:

def EstructurarDB():
    connection = MongoClient(MONGODB_SERVER, MONGODB_PORT)
    db = connection[MONGODB_DB]
    collection = db[MONGODB_COLLECTION]

    prueba = db.News
    eval(
        "db.getCollection('News').find({}, { 'TituloPrincipal': 1 }).sort({ _id: 1 }).forEach(function(record){ db.getCollection('News').remove({ _id: { $gt: record._id }, 'TituloPrincipal': record.TituloPrincipal }); });"
    )
    print(eval("db.News.find().count()"))
    print("it's work")
    connection.close()

我不认为问题出在 eval 函数中,因为当我运行以下代码时,它可以工作:

def EstructurarDB():
    connection = MongoClient(MONGODB_SERVER, MONGODB_PORT)
    db = connection[MONGODB_DB]
    collection = db[MONGODB_COLLECTION]

    prueba = db.News
    print(eval("db.News.find().count()"))
    print("it's work")
    connection.close()

输出:

147
it's work

谢谢。

标签: pythonmongodbpymongo

解决方案


推荐阅读