Searching for a document in MongoDB with Node.js
Being able to insert documents wouldn't do you much good if you didn't have a way to search for documents. MongoDB lets you specify a template on which to match, and returns objects matching that template.
As with insertions and updates, you'll work with a collection of documents, invoking the collection's find method.
How to do it...
Here's an example that finds all documents in the test collection with a call of kf6gpe-7 and prints them to the console:
var mongo = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/test';
mongo.connect(url, function(error, db) {
console.log("mongo.connect returned " + error);
var cursor = collection.find({call: 'kf6gpe-7'});
cursor.toArray(function(error, documents) {
console.log(documents);
db.close();
});
});How it works…
After connecting to the database, we invoke find in the collection, which returns a cursor you can use to iterate through the found values. The find method...