python - 在 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
谢谢。
解决方案
推荐阅读
- fonts - -sSUBSTFONT、-sCIDFSubstFont、-sCIDFSubstPath 不替换 PDF 字体
- javascript - 在 JavaScript ES6 中重新创建 SQL 查询
- react-native - React Native Expo Flatlist:为什么滚动不会在我移开手指的地方停止?
- javascript - 获取“未捕获的 TypeError:无法读取属性 'addEventListener' of null”
- css - 如何防止我的标题布局在 Squarespace 中悬停时移动?
- python - (TypeError: dtype complex128的图像数据不能转换为float)问题
- javascript - 使用 Bootstrap 重叠图像和文本 HTML 的问题
- r - 用R制作二维矢量图
- rust - 为什么我不必声明 x 对于仿射语义和函数类型是可重用/可复制的?
- android - 移动文件后Android“未解析的引用”错误