python - PyMongo 和集合查询的结果
问题描述
所以我正在尝试构建一个查询(在我看来应该非常简单)我来自强类型背景,而 ide 无法帮助我这一事实令人困惑。我正在获取一个结果集,并在下一个查询中使用它。它没有抱怨的 .toString() 选项。
#after copy, remove items from source
def remove_from_source():
ids = tempCollection.find({}, {"_id": 1})
q = "{ _id: { $in: [" + ids + "] } }"
x = sourceCollection.delete_many(q)
print(x.deleted_count + "records deleted.")
我得到的是...
TypeError: can only concatenate str (not "Cursor") to str
但是游标没有字符串选项...
编辑 我现在正在这样做,但它仍然无法正常工作:
# after copy, remove items from source
def remove_from_source():
ids_cursor = tempCollection.find({}, {"_id": 1})
ids = ""
for _id in ids_cursor:
ids = ids + "ObjectId(" + str(_id['_id']) + "),"
ids = ids.rstrip(',')
q = "{ _id: { $in: [" + ids + "] } }"
print(q)
# x = sourceCollection.find(q)
# print(x.count())
# x = sourceCollection.delete_many(q)
# print(x.deleted_count + "records deleted.")
如果我将 q 的输出放入 mongo 查询中,它可以 100% 工作但是 PyMongo 对此并不满意。我可以导入 bson ObjectId,但这仍然不允许我以 pymongo 友好的方式创建 q。
from bson.objectid import ObjectId
解决方案
本,
我认为您应该首先创建一个对象 ID 数组,
ids = []
for _id in ids_cursor:
ids.append(_id['_id'])
然后您可以删除这些项目。
sourceCollection.delete_many({"_id": { "$in": ids }})
推荐阅读
- facebook - Facebook Graph API 在尝试为帐户创建帖子时返回 200 状态代码
- function - RSHINY - 如何将 rhandsontable 写入 csv 文件?
- c++ - 调用 C++ 父类默认构造函数而不是参数化构造函数
- css - 如何在 R Shiny 中调整自定义值框的宽度?
- reactjs - 有没有办法让函数渲染的嵌套组件的引用冒泡?
- shell - Makefile,何时评估 $(shell cat file)?
- discord - 如何让我的 Discord 机器人在运行 join 命令时检查成员是否在语音频道中?
- php - 使用 PHP 将 JSON 数据导入数据库(MySQL)
- elasticsearch - 在 Elasticsearch 中的数组元素中查找最大分数,而不是总和
- string - 从一行复制一个字符串并在另一行的末尾粘贴一个基于模式的大文件