Tuesday, April 28, 2020

Node.js MongoDB Create Insert find document in a collection


Node.js MongoDB


Create a Collection, Insert and Find a document in a Collection

In this tutorial on Node.js and MongoDB, we will learn
  • Creating a Collection
  • What are Collection and Document?
  • Inserting a Document in a Collection
  • Inserting Multiple Documents in a Collection
  • Select(Find) the Documents from Collection

Creating a Collection


First, download the MongoDB Driver, Connect to MongoDB and create a Database, then create a collection in the database.

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";
 
MongoClient.connect(url, function(error, database) {
  if (error) throw error;
  var dbo = database.db("testdb");
  dbo.createCollection("customers", function(error, result) {
    if (error) throw error;
    console.log("Collection created!");
    database.close();
  });
});
/*
Output:
Collection created!
*/


What are Collection and Document?




MongoDB is a NoSQL database, where data is stored as collections of documents. The conventional relational SQL databases store records as rows of data in the tables, and tables related to each other. Document-oriented NoSQL databases like MongoDB have documents that are similar to a record in a collection. A collection is similar to the table. However, the collections are more independent than tables and can contain embedded documents.

MongoDB Collection
Collection


Inserting a document into Collection


To insert single data into a Collection, the insertOne() method is used.

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(error, database) {
  if (error) throw error;
  var dbo = database.db("testdb");
  var doc = { name: "Jhony", dept: "HR", salary: "10000" };
  dbo.collection("employee").insertOne(doc, function(error, result) {
    if (error) throw error;
    console.log("One document is inserted successfully");
    database.close();
  });
});
/*
Output:
One document is inserted successfully
*/

Inserting Multiple documents to the Collection


We can add multiple documents to a Collection together with the insertMany() method. The first parameter of the insertMany() method is an array of document objects.

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(error, database) {
  if (error) throw error;
  var dbo = database.db("testdb");
  //Inserting multiple Documents
  var docs = [
            { name: "Shiva", dept: "Sales", salary: "15000" },
            { name: "Alex", dept: "Sales", salary: "12500" },
            { name: "Viraj", dept: "Marketing", salary: "20000" }
              ];
  dbo.collection("employee").insertMany(docs, function(error, result) {
    if (error) throw error;
    console.log("Multiple Documents inserted successfully");
    database.close();
  });
});
/*
Output:
Multiple Documents inserted successfully
*/

Select(Find) the Documents from Collection


We can use the find() and findOne() method to get the data from the database. This is similar to the SELECT SQL query in conventional relational databases.

findOne() method

This method returns the first document of the collection. The first parameter in this method is the query object.

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(error, database) {
  if (error) throw error;
  var dbo = database.db("testdb");
  dbo.collection("employee").findOne({}, function(error, result) {
    if (error) throw error;
    console.log(result.name+'\t'+result.dept+'\t'+result.salary);
    database.close();
  });
});
/*
Output:
Jhony   HR      10000
*/

find() method


To select entire data from a collection in MongoDB, the find() method can be used. It works like a SELECT statement and returns all occurrences in the selection. The find() method with no parameters is similar to SELECT * in SQL. A first parameter is a query object in this method. For example, an empty query object is used in the following code, to select all documents in the collection employee.

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(error, database) {
  if (error) throw error;
  var dbo = database.db("testdb");
  dbo.collection("employee").find({}).toArray(function(error, result) {
    if (error) throw error;
    console.log("===========All Documents==============");
    for(doc of result)
    console.log(doc.name+'\t'+doc.dept+'\t'+doc.salary);
    database.close();
  });
});
/*
Output:
===========All Documents==============
Jhony   HR      10000
Shiva   Sales   15000
Alex    Sales   12500
Viraj   Marketing       20000
*/


The Second parameter of the method find() is used to get selected (limited) projection of the results.
For example,

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(error, database) {
  if (error) throw error;
  var dbo = database.db("testdb");
  dbo.collection("employee").find({}, { projection: { _id: 1, name: 1, dept:1} }) .toArray(function(error, result) {
    if (error) throw error;
    console.log("===========Selected Documents===========");
    console.log(result);
    database.close();
  });
});
//OUTPUT:
===========Selected Documents===========
[
  { _id: 5ea81ce29e5f1044ec12710b, name: 'Jhony', dept: 'HR' },
  { _id: 5ea8223ffb74b00a3889b2f5, name: 'Shiva', dept: 'Sales' },
  { _id: 5ea8223ffb74b00a3889b2f6, name: 'Alex', dept: 'Sales' },
  { _id: 5ea8223ffb74b00a3889b2f7, name: 'Viraj', dept: 'Marketing' }
]

We can not specify both 0 and 1 values in the same object (except if one of the fields is the _id field). If we provide a field with the value 0, all other fields get the value 1, and vice versa.

const MongoClient = require('mongodb').MongoClient;
const url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(error, database) {
  if (error) throw error;
  var dbo = database.db("testdb");
  dbo.collection("employee").find({}, { projection: { _id: 0, name: 1, dept:1} }) .toArray(function(error, result) {
    if (error) throw error;
    console.log("===========Selected Documents===========");
    console.log(result);
    database.close();
  });
});
//Output
===========Selected Documents===========
[
  { name: 'Jhony', dept: 'HR' },
  { name: 'Shiva', dept: 'Sales' },
  { name: 'Alex', dept: 'Sales' },
  { name: 'Viraj', dept: 'Marketing' }
]