Tutorial by Examples

Connect to MongoDB, print 'Connected!' and close the connection. const MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:27017/test'; MongoClient.connect(url, function(err, db) { // MongoClient method 'connect' if (err) throw new Error(err); console.log(&q...
Insert a document called 'myFirstDocument' and set 2 properties, greetings and farewell const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017/test'; MongoClient.connect(url, function (err, db) { if (err) throw new Error(err); db.collection('myCollect...
Get all documents in the collection 'myCollection' and print them to the console. const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017/test'; MongoClient.connect(url, function (err, db) { if (err) throw new Error(err); var cursor = db.collection('my...
Find a document with the property { greetings: 'Hellu' } and change it to { greetings: 'Whut?' } const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017/test'; MongoClient.connect(url, function (err, db) { if (err) throw new Error(err); db.collecti...
Delete a document with the property { greetings: 'Whut?' } const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017/test'; MongoClient.connect(url, function (err, db) { if (err) throw new Error(err); db.collection('myCollection').deleteOne(// Delete...
Delete ALL documents with a 'farewell' property set to 'okay'. const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017/test'; MongoClient.connect(url, function (err, db) { if (err) throw new Error(err); db.collection('myCollection').deleteMany(// M...
MongoDB.connect('mongodb://localhost:27017/databaseName', function(error, database) { if(error) return console.log(error); const collection = database.collection('collectionName'); collection.insert({key: 'value'}, function(error, result) { console.log(error, result); }); }...
const MongoDB = require('mongodb'); MongoDB.connect('mongodb://localhost:27017/databaseName') .then(function(database) { const collection = database.collection('collectionName'); return collection.insert({key: 'value'}); }) .then(function(result) { co...

Page 1 of 1