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, ...

Get JavaScript JSON Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.