Querying and searching for documents in a MongoDB collection is pretty straightforward. Using the find() function by itself with no parameters will return every document in the collection. To narrow down the search results, you can provide a JSON object as the first parameter with as much or as little specific information to match against as you wish, as shown in the following code:
> db.newCollection.find({ name: 'Jason Krol' }) { "_id" : ObjectId("533dfb9433519b9339d3d9e1"), "name" : "Jason
Krol", "website" : "http://kroltech.com" }
You can include additional parameters to make the search more precise:
> db.newCollection.find({ name: 'Jason Krol', website:
'http://kroltech.com'}){ "_id" : ObjectId("533dfb9433519b9339d3d9e1"), "name" : "Jason
Krol", "website" : "http://kroltech.com" }
> db.newCollection.find({ name: 'Jason Krol' }, { name: true }) { "_id" : ObjectId("533dfb9433519b9339d3d9e1"), "name" : "Jason Krol"
}> db.newCollection.find({ name: 'Jason Krol' }, { name: true, _id:
false }) { "name" : "Jason Krol" }
Additionally, you can use query operators to search for things that are within ranges. These include greater than (or equal to) and less than (or equal to). If you want to perform a search against a collection of homework, and you want to find every document with a score within the B range (80-89), you can execute the following search:
> db.homework_scores.find({ score: { $gte: 80, $lt: 90 } })
Finally, you can use regex while performing a search to return multiple matching documents:
> db.newCollection.find({ name: { $regex: 'Krol'} })
The preceding query will return every document that contains the word Krol. You can get as advanced as you want with regex statements.
If you know that you are going to be returning multiple documents on a query and only want the first result, use findOne() in place of a regular find() operation.