Confusing English for count in Docs

20 views
Skip to first unread message

Sam Millman

unread,
Jul 10, 2014, 8:50:34 AM7/10/14
to mongod...@googlegroups.com
On: http://docs.mongodb.org/manual/reference/method/db.collection.count/

It says:

method does not perform the find() operation but instead counts and returns the number of results that match a query.

db.c.find().count() won't perform a find command will it?

Does that mean that db.c.count() is somehow more optimal?

Will Berkeley

unread,
Jul 11, 2014, 11:22:25 AM7/11/14
to mongod...@googlegroups.com
Hi Sammaye. If you check out the code for db.collection.count in the mongo shell:

> db.test.count
function ( x ){
   
return this.find( x ).count();
}

you will find that db.collection.count(query) is equivalent to db.collection.find.count(). db.collection.find(query).count() does not perform the find operation. It executes a count database command. You can also see this in the shell by printing the code:

> db.test.find().count
function ( applySkipLimit ) {
   
var cmd = { count: this._collection.getName() };
   
if ( this._query ) { ... }
   
...
   
var res = this._db.runCommand( cmd );
   
if( res && res.n != null ) return res.n;
   
throw "count failed: " + tojson( res );
}

Remember that db.collection.find(query) returns a cursor, not the actual result set, so the query isn't performed just by executing db.collection.find(query). It appears that way in the shell, e.g.

> db.test.find({"a.x" : 1})
{ "_id" : ObjectId("53bc3258d519a03e56d6906f"), "a" : [ { "x" : 1 }, { "y" : 2 }, { "z" : 3 } ] }

because the shell prints out the result of each expression after it evaluates it, and doing that with a cursor executes the query to get some results to print.

-Will
Reply all
Reply to author
Forward
0 new messages