Node MongoDB

Docs

//UNTESTED CODE

//https://mongodb.github.io/node-mongodb-native/3.2/reference/ecmascriptnext/crud/

Install MongoDB driver

npm install mongodb --save

Connect to MongoDB

var MongoClient = require('mongodb').MongoClient;
// Connection URL
var url = 'mongodb://localhost:27017';
/*var url = `mongodb://
${dbUserName}:${dbPassword}
@localhost:27017/?authSource=admin`;*/
// Use connect method to connect to the server
MongoClient.connect(url)
.then((client) => {
var db = client.db('dbName')
console.log("Connected successfully to server");
db.close();
})
.catch((err) => {});

Inserting in to MongoDB

db.collection('documents')
.insertMany([{
a: 1
}, {
a: 2
}, {
a: 3
}])
.then((result) => {
console.log("Inserted 3 documents into the collection");
})
.catch((err) => {})
  • The insert command returns an object with the following fields:

    • result Contains the result document from MongoDB
    • ops Contains the documents inserted with added _id fields
    • connection Contains the connection used to perform the insert

Find documents

db.collection('documents')
.find({}) //it returns cursor
.project({})
.toArray()

Update documents

db.collection('documents')
.updateOne({
"item": "box"
}, {
$set: {
"qty": 99
}
})
.then((res) => {
console.log(res)
})
.catch((err) => {})