MongoDB: Queries Cheat Sheet

db.collection.find(<query>)Find the documents matching the <query> criteria in the collection. If the <query> criteria is not specified or is empty (i.e {} ), the read operation selects all documents in the collection.The following example selects the documents in the users collection with the name field equal to "Joe":copycopiedcoll = db.users; coll.find( { name: “Joe” } ); For more information on specifying the <query> criteria, see Specify Equality Condition.
db.collection.find(<query>, <projection>)Find documents matching the <query> criteria and return just specific fields in the <projection>.The following example selects all documents from the collection but returns only the name field and the _id field. The _id is always returned unless explicitly specified to not return.copycopiedcoll = db.users; coll.find( { }, { name: true } ); For more information on specifying the <projection>, see Project Fields to Return from Query.
db.collection.find().sort(<sort order>)Return results in the specified <sort order>.The following example selects all documents from the collection and returns the results sorted by the name field in ascending order (1). Use -1 for descending order:copycopiedcoll = db.users; coll.find().sort( { name: 1 } );
db.collection.find(<query>).sort(<sort order>)Return the documents matching the <query> criteria in the specified <sort order>.
db.collection.find( ... ).limit( <n> )Limit result to <n> rows. Highly recommended if you need only a certain number of rows for best performance.
db.collection.find( ... ).skip( <n> )Skip <n> results.
db.collection.count()Returns total number of documents in the collection.
db.collection.find(<query>).count()Returns the total number of documents that match the query.The count() ignores limit() and skip(). For example, if 100 records match but the limit is 10, count() will return 100. This will be faster than iterating yourself, but still take time.
db.collection.findOne(<query>)Find and return a single document. Returns null if not found.The following example selects a single document in the users collection with the name field matches to "Joe":copycopiedcoll = db.users; coll.findOne( { name: “Joe” } ); Internally, the findOne() method is the find() method with a limit(1).

Leave a Reply

Your email address will not be published. Required fields are marked *