Example query in mongoDB with nodejs

Filter the Result

When finding documents in a collection, you can filter the result by using a query object.

The first argument of the find() method is a query object, and is used to limit the search.

Example: Find documents with the address "Park Lane 38"

 

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://192.168.1.122:27017/";

MongoClient.connect(url, function(err, db) {

  if (err) throw err;

  var dbo = db.db("mydb");

  /*Return only the documents with the address "Park Lane 38":*/

  var query = { address: "Park Lane 38" };

  dbo.collection("customers").find(query).toArray(function(err, result) {

    if (err) throw err;

    console.log(result);

    db.close();

  });

});

 

Run and result:

 

C:\Nodejs>node mongodbQueryString.js

[ { _id: 5add95feece97026743f71e5,

    name: 'name11',

    address: 'Park Lane 38' } ]

 

Filter With Regular Expressions

You can write regular expressions to find exactly what you are searching for.

Regular expressions can only be used to query strings.

To find only the documents where the "address" field starts with the letter "S", use the regular expression /^S/

Example: Find documents where the address starts with the letter "S"

 

var MongoClient = require('mongodb').MongoClient;

var url = "mongodb://192.168.1.122:27017/";

MongoClient.connect(url, function(err, db) {

  if (err) throw err;

  var dbo = db.db("mydb");

  /*Return only the documents with the address "Park Lane 38":*/

  var query = { address: /^S/ };

  dbo.collection("customers").find(query).toArray(function(err, result) {

    if (err) throw err;

    console.log(result);

    db.close();

  });

});

 

Run and result:

 

C:\Nodejs>node mongodbQueryString.js

[ { _id: 5add95feece97026743f71e2,

    name: 'name8',

    address: 'Sky st 331' },

  { _id: 5add95feece97026743f71e8,

    name: 'name14',

    address: 'Sideway 1633' } ]