Find or Query Data with Node.js

Overview

You can use the find method to issue a query to retrieve data from a collection in MongoDB. All queries in MongoDB have the scope of a single collection.

Queries can return all documents in a collection or only the documents that match a specified filter or criteria. You can specify the filter or criteria in a document and pass as a parameter to the find method.

The find method returns query results in a cursor, which is an iterable object that yields documents.

Prerequisites

The examples in this section use the restaurants collection in the test database. For instructions on populating the collection with the sample dataset, see Import Example Dataset.

In the node shell, define the following variables to access the required modules as well as to initialize url to the MongoDB uri.

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/test';

Query for All Documents in a Collection

To return all documents in a collection, call the find method without a criteria document. For example, the following operation queries for all documents in the restaurants collection.

Define a findRestaurants function as follows:

var findRestaurants = function(db, callback) {
   var cursor =db.collection('restaurants').find( );
   cursor.each(function(err, doc) {
      assert.equal(err, null);
      if (doc != null) {
         console.dir(doc);
      } else {
         callback();
      }
   });
};

Call the findRestaurants function.

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  findRestaurants(db, function() {
      db.close();
  });
});

The result set contains all documents in the restaurants collection.

Specify Equality Conditions

The query condition for an equality match on a field has the following form:

{ <field1>: <value1>, <field2>: <value2>, ... }

If the <field> is in an embedded document or an array, use dot notation to access the field.

Query by a Top Level Field

The following operation finds documents whose borough field equals "Manhattan".

Define a findRestaurants function.

var findRestaurants = function(db, callback) {
   var cursor =db.collection('restaurants').find( { "borough": "Manhattan" } );
   cursor.each(function(err, doc) {
      assert.equal(err, null);
      if (doc != null) {
         console.dir(doc);
      } else {
         callback();
      }
   });
};

Call the findRestaurants function.

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  findRestaurants(db, function() {
      db.close();
  });
});

The result set includes only the matching documents.

Query by a Field in an Embedded Document

To specify a condition on a field within an embedded document, use the dot notation. Dot notation requires quotes around the whole dotted field name. The following operation specifies an equality condition on the zipcode field in the address embedded document.

Define a findRestaurants function as follows:

var findRestaurants = function(db, callback) {
   var cursor =db.collection('restaurants').find( { "address.zipcode": "10075" } );
   cursor.each(function(err, doc) {
      assert.equal(err, null);
      if (doc != null) {
         console.dir(doc);
      } else {
         callback();
      }
   });
};

Call the findRestaurants function.

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);

  findRestaurants(db, function() {
      db.close();
  });
});

The result set includes only the matching documents.

For more information on querying on fields within an embedded document, see Query on Embedded Documents.

Query by a Field in an Array

The grades array contains embedded documents as its elements. To specify a condition on a field in these documents, use the dot notation. Dot notation requires quotes around the whole dotted field name. The following queries for documents whose grades array contains an embedded document with a field grade equal to "B".

Define a findRestaurants function as follows:

var findRestaurants = function(db, callback) {
   var cursor =db.collection('restaurants').find( { "grades.grade": "B" } );
   cursor.each(function(err, doc) {
      assert.equal(err, null);
      if (doc != null) {
         console.dir(doc);
      } else {
         callback();
      }
   });
};

Call the findRestaurants function.

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);

  findRestaurants(db, function() {
      db.close();
  });
});

The result set includes only the matching documents.

For more information on querying on arrays, such as specifying multiple conditions on array elements, see Query on Arrays and $elemMatch.

Specify Conditions with Operators

MongoDB provides operators to specify query conditions, such as comparison operators. Although there are some exceptions, such as the $or and $and conditional operators, query conditions using operators generally have the following form:

{ <field1>: { <operator1>: <value1> } }

For a complete list of the operators, see query operators.

Greater Than Operator ($gt)

Query for documents whose grades array contains an embedded document with a field score greater than 30.

Define a findRestaurants function as follows:

var findRestaurants = function(db, callback) {
   var cursor =db.collection('restaurants').find( { "grades.score": { $gt: 30 } } );
   cursor.each(function(err, doc) {
      assert.equal(err, null);
      if (doc != null) {
         console.dir(doc);
      } else {
         callback();
      }
   });
};

Call the findRestaurants function.

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);

  findRestaurants(db, function() {
      db.close();
  });
});

The result set includes only the matching documents.

Less Than Operator ($lt)

Query for documents whose grades array contains an embedded document with a field score less than 10.

Define a findRestaurants function as follows:

var findRestaurants = function(db, callback) {
   var cursor =db.collection('restaurants').find( { "grades.score": { $lt: 10 } } );
   cursor.each(function(err, doc) {
      assert.equal(err, null);
      if (doc != null) {
         console.dir(doc);
      } else {
         callback();
      }
   });
};

Call the findRestaurants function.

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);

  findRestaurants(db, function() {
      db.close();
  });
});

The result set includes only the matching documents.

Combine Conditions

You can combine multiple query conditions in logical conjunction (AND) and logical disjunctions (OR).

Logical AND

You can specify a logical conjunction (AND) for a list of query conditions by separating the conditions with a comma in the conditions document.

Define the findRestaurants function as follows:

var findRestaurants = function(db, callback) {
   var cursor =db.collection('restaurants').find(
     { "cuisine": "Italian", "address.zipcode": "10075" }
   );
   cursor.each(function(err, doc) {
      assert.equal(err, null);
      if (doc != null) {
         console.dir(doc);
      } else {
         callback();
      }
   });
};

Call the findRestaurants function.

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);

  findRestaurants(db, function() {
      db.close();
  });
});

The result set includes only the documents that matched all specified criteria.

Logical OR

You can specify a logical disjunction (OR) for a list of query conditions by using the $or query operator.

Define the findRestaurants function as follows:

var findRestaurants = function(db, callback) {
   var cursor =db.collection('restaurants').find(
       { $or: [ { "cuisine": "Italian" }, { "address.zipcode": "10075" } ] }
   );
   cursor.each(function(err, doc) {
      assert.equal(err, null);
      if (doc != null) {
         console.dir(doc);
      } else {
         callback();
      }
   });
};

Call the findRestaurants function.

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);

  findRestaurants(db, function() {
      db.close();
  });
});

The result set includes only the documents that match either conditions.

Sort Query Results

To specify an order for the result set, append the sort() method to the query. Pass to sort() method a document which contains the field(s) to sort by and the corresponding sort type, e.g. 1 for ascending and -1 for descending.

Define a findRestaurants function to retrieve all documents in the restaurants collection, sorted first by the borough field in ascending order, and then, within each borough, by the "address.zipcode" field in ascending order.

var findRestaurants = function(db, callback) {
   var cursor =db.collection('restaurants').find().sort( { "borough": 1, "address.zipcode": 1 } );
   cursor.each(function(err, doc) {
      assert.equal(err, null);
      if (doc != null) {
         console.dir(doc);
      } else {
         callback();
      }
   });
};

Call the findRestaurants function.

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);

  findRestaurants(db, function() {
      db.close();
  });
});

The operation returns the results sorted in the specified order.

Additional Information

In the Node.js documentation, see find, Cursor, and sort.

In the MongoDB Manual, see also Query Documents tutorial, Projection tutorial, Query and Projection Operators reference, and Cursor Methods.