To create a database in MongoDB, start by creating a MongoClient object,
then specify a connection URL with the correct IP address and the name of the
the database you want to create.
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://127.0.0.1:27017/";
1. Create DataBase In NodeJs | MongoDB
// MongoDB will create the database if
it does not exist, and make a connection to it.
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
2. Create Collection In NodeJs | MongoDB
// To create a collection in MongoDB, use the createCollection() method:
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.createCollection("user", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
});
3. Insert In NodsJs | MongoDB
/*Insert Into Collection
The first parameter of the insertOne() method is an object
containing the name(s) and value(s) of each field in the
the document you want to insert*/
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myobj = { name: "Company Inc", address: "Highway 37" };
dbo.collection("customers").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});
/*Insert Multiple Documents
To insert multiple documents into a collection in MongoDB,
we use the insertMany() method. The first parameter of the
insertMany() method is an array of objects,
containing the data you want to insert.*/
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myobj = [
{ name: 'abc', address: 'new 71'},
{ name: 'xyz', address: 'lost 4'},
{ name: 'jon', address: 'test st 6562'},
];
dbo.collection("user").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log("Number of documents inserted: " + res.insertedCount);
db.close();
});
});
4. Find In NodeJs | MongoDB
// Full Documentation - https://www.turbo360.co/docs
The first parameter of the findOne() method is a query object.
In this example, we use an empty query object, which selects all
documents in a collection
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("customers").findOne({}, function(err, result) {
if (err) throw err;
console.log(result.name);
db.close();
});
});
//The find() method returns all occurrences in the selection.
The first parameter of the find() method is a query object.
In this example, we use an empty query object,
which selects all documents in the collection.
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("customers").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
5. Drop Collection In NodeJs | MongoDB
//The drop() method takes a callback function containing the error object
and the result parameter which returns true if
the collection was dropped successfully, otherwise, it returns false.
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("user").drop(function(err, delOK) {
if (err) throw err;
if (delOK) console.log("Collection deleted");
db.close();
});
});
//The dropCollection() method takes two parameters:
the name of the collection and a callback function
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.dropCollection("customers", function(err, delOK) {
if (err) throw err;
if (delOK) console.log("Collection deleted");
db.close();
});
});
6. Delete In NodeJs | MongoDB
To delete a record, or document as it is called in MongoDB,
we use the deleteOne() method.
Note: If the query finds more than one document,
only the first occurrence is deleted.
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myquery = { address: 'Mountain 21' };
dbo.collection("customers").deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log("1 document deleted");
db.close();
});
});
//To delete more than one document, use the deleteMany() method.
Note: Delete all documents were the address starts with the letter "G":
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myquery = { address: /^G/ };
dbo.collection("customers").deleteMany(myquery, function(err, obj) {
if (err) throw err;
console.log(obj.result.n + " document(s) deleted");
db.close();
});
});
7. Sort In NodeJs | MongoDB
//Use the sort() method to sort the result in ascending or descending
order.
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var mysort = { name: 1 };
dbo.collection("customers").find().sort(mysort).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
8. Query In NodeJs | MongoDB
// Full Documentation - https://www.turbo360.co/docs
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
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var query = { address: "Park Lane 38" };
dbo.collection("user").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
//To find only the documents where the "address" field starts with the
letter "G", use the regular expression /^G/
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var query = { address: /^G/ };
dbo.collection("user").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
9. Limit In NodeJs | MongoDB
//The limit() method takes one parameter,
a number defining how many documents to return.
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("customers").find().limit(5).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
10. Update In NodeJs | MongoDB
//The first parameter of the updateOne() method is a query
object defining which document to update
Note: If the query finds more than one record,
only the first occurrence is updated.
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myquery = { address: "Valley 345" };
var newvalues = { $set: {name: "Mickey", address: "Canyon 123" } };
dbo.collection("user").updateOne(myquery, newvalues, function(err, res) {
if (err) throw err;
console.log("1 document updated");
db.close();
});
});
Update Only Specific Fields
When using the $set operator, only the specified fields are updated:
...
var myquery = { address: "Valley 345" };
var newvalues = { $set: { address: "Canyon 123" } };
dbo.collection("user").updateOne(myquery, newvalues, function(err, res) {
...
Update Many Documents
To update all documents that meet the criteria of the query,
use the updateMany() method.
Note: Update all documents where the name starts with the letter "G":
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myquery = { address: /^G/ };
var newvalues = {$set: {name: "Minnie"} };
dbo.collection("user").updateMany(myquery, newvalues, function(err, res) {
if (err) throw err;
console.log(res.result.nModified + " document(s) updated");
db.close();
});
});
11. Join In NodeJs | MongoDB
Join the matching "userAddress" address to the "user" collection
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection('user').aggregate(
[
{ $lookup:
{
from: 'userAddress',
localField: 'address_id',
foreignField: '_id',
as: 'address'
}
}
]).toArray(function(err, res) {
if (err) throw err;
console.log(JSON.stringify(res));
db.close();
});
});
.