如何使用 pymongo 获取仅包含 ObjectId 的列表?

How do I get a list of just the ObjectId's using pymongo?

我有以下代码:

client = MongoClient()
data_base = client.hkpr_restore
agents_collection = data_base.agents
agent_ids = agents_collection.find({},{"_id":1})

这给了我一个结果:

{u'_id': ObjectId('553020a8bf2e4e7a438b46d9')}
{u'_id': ObjectId('553020a8bf2e4e7a438b46da')}
{u'_id': ObjectId('553020a8bf2e4e7a438b46db')}

我如何才能获得 ObjectId,然后才能使用每个 ID 搜索另一个集合?

尝试仅使用 _ids 创建列表理解,如下所示:

>>> client = MongoClient()
>>> data_base = client.hkpr_restore
>>> agents_collection = data_base.agents
>>> result = agents_collection.find({},{"_id":1})
>>> agent_ids = [x["_id"] for x in result]
>>> 
>>> print agent_ids
[ ObjectId('553020a8bf2e4e7a438b46d9'),  ObjectId('553020a8bf2e4e7a438b46da'),  ObjectId('553020a8bf2e4e7a438b46db')]
>>>

使用distinct

In [27]: agent_ids = agents_collection.find().distinct('_id')

In [28]: agent_ids
Out[28]: 
[ObjectId('553662940acf450bef638e6d'),
 ObjectId('553662940acf450bef638e6e'),
 ObjectId('553662940acf450bef638e6f')]

In [29]: agent_id2 = [str(id) for id in agents_collection.find().distinct('_id')]

In [30]: agent_id2
Out[30]: 
['553662940acf450bef638e6d',
 '553662940acf450bef638e6e',
 '553662940acf450bef638e6f']

我想添加一些比查询所有 _id 更通用的内容。

import bson
[...]
results = agents_collection.find({}})
objects = [v for result in results for k,v in result.items()
          if isinstance(v,bson.objectid.ObjectId)]

上下文:在 gridfs 中保存对象会创建 ObjectId,以检索所有对象以供进一步查询,此功能帮了我的忙。

我按照这个 answer 解决了这个问题。 向查找语法添加提示,然后简单地遍历游标 returned.

db.c.find({},{_id:1}).hint(_id:1);

我猜如果没有提示,光标会在迭代时取回整个文档,导致迭代非常慢。 有了提示,光标只会返回 return ObjectId,并且迭代会很快完成。

背景是我正在处理一项 ETL 作业,该作业需要将一个 mongo 集合同步到另一个集合,同时根据某些条件修改数据。 Object id的总数大约是 100000000.

我尝试使用 distinct 但出现以下错误:

Error in : distinct too big, 16mb cap

我尝试使用聚合并按照其他类似问题的回答做了 $group。只会遇到一些内存消耗错误。

虽然我没有搜索 _id,但我正在提取另一个字段。我发现这个方法很快(假设你在该字段上有一个索引):

list_of_strings = {x.get("MY_FIELD") for x in db.col.find({},{"_id": 0, "MY_FIELD": 1}).hint("MY_FIELDIdx")}

其中 MY_FIELDIdx 是我要提取的字段的索引名称。