Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PYMONGO - How do I use the query $in operator with MongoIDs?

So I am trying to use the $in operator in Pymongo where I want to search with a bunch of MongoIDs.

First I have this query to find an array of MongoIDs:

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

If I print the findUsers['f'] it looks like this:

[ObjectId('53b2dc0b24c4310292e6def5'), ObjectId('53b6dbb654a7820416a12767')]

These object IDs are user ids and what I want to do is to find all users that are in the users collection with this array of ObjectID. So my thought was this:

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

However when I print the foundUsers the outcome is this:

<pymongo.cursor.Cursor object at 0x10d972c50>

which is not what I normally get when I print a query out :(

What am I doing wrong here?

Many thanks.

Also just for you reference, I have queried in the mongo shell and it works as expected:

db.users.find({_id: {$in:[ObjectId('53b2dc0b24c4310292e6def5'), ObjectId('53b6dbb654a7820416a12767')]}})
like image 938
jonprasetyo Avatar asked Jul 04 '14 17:07

jonprasetyo


1 Answers

You are encountering the difference between findOne() and find() in MongoDB. findOne returns a single document. find() returns a mongoDB cursor. Normally you have to iterate over the cursor to show the results. The reason your code works in the mongo shell is that the mongo shell treats cursors differently if they return 20 documents or less - it handles iterating over the cursor for you:

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/

The pymongo manual page on iterating over cursors would probably be a good place to start:

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

but here's a piece of code that should illustrate the basics for you. After your call to find() run this:

for doc in findUsers:
    print(doc)
like image 170
John Petrone Avatar answered Nov 04 '22 13:11

John Petrone