MongoDB: Retrieving the first document in a collection

mongodb

I'm new to Mongo, and I'm trying to retrieve the first document from a find() query:

> db.scores.save({a: 99});
> var collection = db.scores.find();
[ 
  {   "a" : 99,   "_id" : {   "$oid" : "51a91ff3cc93742c1607ce28"   }   }
]
> var document = collection[0];
JS Error: result is undefined

This is a little weird, since a collection looks a lot like an array. I'm aware of retrieving a single document using findOne(), but is it possible to pull one out of a collection?

Best Answer

The find method returns a cursor. This works like an iterator in the result set. If you have too many results and try to display them all in the screen, the shell will display only the first 20 and the cursor will now point to the 20th result of the result set. If you type it the next 20 results will be displayed and so on.

In your example I think that you have hidden from us one line in the shell.

This command

> var collection = db.scores.find();

will just assign the result to the collection variable and will not print anything in the screen. So, that makes me believe that you have also run:

> collection

Now, what is really happening. If you indeed have used the above command to display the content of the collection, then the cursor will have reached the end of the result set (since you have only one document in your collection) and it will automatically close. That's why you get back the error.

There is nothing wrong with your syntax. You can use it any time you want. Just make sure that your cursor is still open and has results. You can use the collection.hasNext() method for that.