首页 > 解决方案 > 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

标签: pythonmongodbpymongo

解决方案


本,

我认为您应该首先创建一个对象 ID 数组,

ids = [] 
for _id in ids_cursor:
    ids.append(_id['_id']) 

然后您可以删除这些项目。

sourceCollection.delete_many({"_id": { "$in": ids }})


推荐阅读