所以我尝试在Pymongo中使用$in操作符,在这里我想用一堆mongoid进行搜索。在
首先,我用这个查询来查找mongoid数组:
findUsers = db.users.find_one({'_id':user_id},{'_id':0, 'f':1})
如果我打印findUsers['f']
,它看起来像这样:
这些对象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')]}})
您在MongoDB中遇到了findOne()和find()之间的区别。findOne返回单个文档。find()返回一个mongoDB游标。通常,您必须在光标上迭代以显示结果。您的代码在mongo shell中工作的原因是,如果游标返回20个或更少的文档,mongo shell会以不同的方式对待它们-它会为您处理在光标上的迭代:
http://docs.mongodb.org/manual/core/cursors/
关于遍历游标的pymongo手册页可能是一个很好的起点:
http://api.mongodb.org/python/current/api/pymongo/cursor.html
但是这里有一段代码应该可以为您说明一些基本知识。调用find()后,运行以下命令:
相关问题 更多 >
编程相关推荐