SiteCozy

  • My account

How to retrieve data from MongoDB with NodeJS

2018-09-26

To retrieve data from the MongoDB database we will use find, findOne with nodeJS promise. 

In the first example, we use findOne which will return the first occurrence where “this”:1 in the collection test in the database testdb. This will be an array including the _id and the fields of the document.

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

// Connection url
const url = 'mongodb://192.168.1.203:27017';
options = {
    useNewUrlParser: true
};

MongoClient.connect(url, options).then(function (ok) {
        
       db1 = ok;
       dbName = 'testdb';
        return db1.db(dbName).collection('test').findOne({"this":1});

    })
    .then(function (dbs) {
console.log(dbs);
db1.close();
    });

This will return the data in nodeJS

$ node test.js
{ _id: 5bab60e785f572e55fe09165, this: 1, another: 'dfjfjdfdf' }

You can also use find().toArray to return all the documents with a field equals to the same value (here this: 1).

const MongoClient = require('mongodb').MongoClient;
// Connection url
const url = 'mongodb://192.168.1.203:27017';
options = {
    useNewUrlParser: true
};

MongoClient.connect(url, options).then(function (ok) {
        
       db1 = ok;
       dbName = 'testdb';
        return db1.db(dbName).collection('test').find({"this":1}).toArray();

    })
    .then(function (dbs) {
console.log(dbs);
db1.close();
    });

This will return the following result in an array because I inserted three identical documents using insertOne:

$ node test.js
[ { _id: 5bab60e785f572e55fe09165, this: 1, another: 'dfjfjdfdf' },
  { _id: 5bab61018df000e560655d2d, this: 1, another: 'dfjfjdfdf' },
  { _id: 5bab6110b8724ae561d7191d, this: 1, another: 'dfjfjdfdf' } ]

Related Posts:

  • How to fix the cyclic dependancy error in nodeJS/mongodb
  • How to update several doc. in MongoDB with NodeJS
  • How to insert one doc in MongoDB with NodeJS
Download our Broken link checker freeware here Buy a license key for the Sitecozy broken link checker

Customer Login

Lost password?

Categories

  • Webmaster advice
  • SEO advice
  • Web hosting
  • SiteCozy link checker KB
  • WordPress theme & plugin reviews
  • All articles
Disclosure: We are a professional review site that receives compensation from the companies whose products we review. We test each product thoroughly and give high marks to only the very best. We are independently owned and the opinions expressed here are our own.

Copyright Sitecozy 2018