Make sure you have node.js installed. I’ve combine all code from w3schools.com into single file.
mkdir test-mongodb cd test-mongo-db npm init
Source: Node.js MongoDB Get Started
Add mongodb module:
npm install mongodb
Create a file (by default index.js):
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
// // does nothing
// MongoClient.connect(url, function(err, db) {
// if (err) throw err;
// console.log("Database created!");
// db.close();
// });
// does nothing
// MongoClient.connect(url, function(err, db) {
// if (err) throw err;
// var dbo = db.db("mydb");
// dbo.createCollection("customers", function(err, res) {
// if (err) throw err;
// console.log("Collection created!");
// db.close();
// });
// });
// remove all previously inserted documents
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("customers").deleteMany(function(err, res) {
if (err) throw err;
console.log("Collection emptied :-)!");
db.close();
});
});
// insert single document
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myobj = { name: "some name", address: "somebody's address" };
dbo.collection("customers").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log(`${res.insertedCount} document(s) inserted`);
db.close();
});
});
// insert multiple documents
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var myobj = [
{ name: "local business", address: "Lehigh Acres" },
{ name: "family", address: "Fort Myers" },
{ name: "friends", address: "Naples, FL" },
];
dbo.collection("customers").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log(`${res.insertedCount} document(s) inserted`);
db.close();
});
});
// show all records from 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('-'.repeat(80));
console.log(result);
db.close();
});
});
// conditional query
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
var query = { address: "Lehigh Acres" };
dbo.collection("customers").find(query).toArray(function(err, result) {
if (err) throw err;
console.log('-'.repeat(80));
console.log(result);
db.close();
});
});
For Visual Code, go to terminal Ctrl+`, run “node .” and you should see add documents/records to the MongoDB. Some warning could be displayed 🙁