PYMONGO如何在mongoid中使用查询$in运算符?

2024-10-01 09:29:18 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我尝试在Pymongo中使用$in操作符,在这里我想用一堆mongoid进行搜索。在

首先,我用这个查询来查找mongoid数组:

findUsers = db.users.find_one({'_id':user_id},{'_id':0, 'f':1})

如果我打印findUsers['f'],它看起来像这样:

^{pr2}$

这些对象id是用户id,我要做的是用这个ObjectID数组查找users集合中的所有用户。所以我的想法是:

foundUsers = db.users.find({'_id':{'$in':findUsers['f']}})

但是,当我打印foundUsers时,结果是:

<pymongo.cursor.Cursor object at 0x10d972c50>

这不是我打印查询时通常得到的结果:(

我做错什么了?在

非常感谢。在

同样仅供参考,我在mongo shell中进行了查询,其工作情况如预期:

db.users.find({_id: {$in:[ObjectId('53b2dc0b24c4310292e6def5'), ObjectId('53b6dbb654a7820416a12767')]}})

Tags: 用户iniddb数组findoneusers
1条回答
网友
1楼 · 发布于 2024-10-01 09:29:18

您在MongoDB中遇到了findOne()和find()之间的区别。findOne返回单个文档。find()返回一个mongoDB游标。通常,您必须在光标上迭代以显示结果。您的代码在mongo shell中工作的原因是,如果游标返回20个或更少的文档,mongo shell会以不同的方式对待它们-它会为您处理在光标上的迭代:

Cursors

In the mongo shell, the primary method for the read operation is the db.collection.find() method. This method queries a collection and returns a cursor to the returning documents.

To access the documents, you need to iterate the cursor. However, in the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times [1] to print up to the first 20 documents in the results.

http://docs.mongodb.org/manual/core/cursors/

关于遍历游标的pymongo手册页可能是一个很好的起点:

http://api.mongodb.org/python/current/api/pymongo/cursor.html

但是这里有一段代码应该可以为您说明一些基本知识。调用find()后,运行以下命令:

for doc in findUsers:
    print(doc)

相关问题 更多 >