Reputation: 55729
I have a collection users
in mongodb. I am using the node/mongodb API.
In my node.js if I go:
var users = db.collection("users");
and then
users.findOne({ ... })
Is this idiomatic and efficient?
I want to avoid loading all users into application memory.
Upvotes: 2
Views: 70
Reputation: 78
In Mongo, collection.find()
returns a cursor
, which is an abstract representation of the results that match your query. It doesn't return your results over the wire until you iterate over the cursor by calling cursor.next()
. Before iterating over it, you can, for instance, call cursor.limit(x)
to limit the number of results that it is allowed to return.
collection.findOne()
is effectively just a shortcut version of collection.find().limit(1).next()
. So the cursor is never allowed to return more than the one result.
As already explained, the collection
object itself is a facade allowing access to the collection, but which doesn't hold any actual documents in memory.
findOne()
is very efficient, and it is indeed idiomatic, though IME it's more used in dev/debugging than in real application code. It's very useful in the CLI, but how often does a real application need to just grab any one document from a collection? The only case I can think of is when a given query can only ever return one document (i.e. an effective primary key).
Further reading: Cursors, Read Operations
Upvotes: 3
Reputation: 43884
Yes, that should only load one user into memory.
The collection object is exactly that, it doesn't return all users when you create a new collection object, only when you either use a findOne
or you iterate a cursor from the return of a find
.
Upvotes: 1