Firstly, make sure you have Node.js, MongoDB and MongoDB Node.js driver installed.
Connecting to MongoDB
Once you have the MongoDB Node.js driver installed, you can use it to interact with your MongoDB cluster. You can connect to your MongoDB server by using the MongoClient’s `connect` method.
Here’s a simple example:
```
const { MongoClient } = require(‘mongodb’);
// Connection URL
const url = ‘mongodb://localhost:27017’;
// Database Name
const dbName = ‘mydatabase’;
(async function() { let client;
try { client = await MongoClient.connect(url); console.log(“Connected correctly to server”); const db = client.db(dbName); } catch (err) { console.log(err.stack); } if (client) { client.close(); } })(); ```Operations on MongoDB
MongoDB Node.js driver provides a set of operations you can use to manipulate the database. These are similar to MongoDB commands except for that in Node.js you are calling a method instead.
Here’s some examples:
// Insert a Document
```
const collection = db.collection(‘documents’);
const doc = {a : 1};
collection.insertOne(doc, function(err, result) {
assert.equal(err, null);
console.log(“Inserted a document into the ‘documents’ collection.”);
});
```
// Insert Multiple Documents
```
const collection = db.collection(‘documents’);
const docs = [{ a: 1 }, { a: 2 }, { a: 3 }];
collection.insertMany(docs, function(err, result) {
assert.equal(err, null);
console.log(“Inserted 3 documents into the ‘documents’ collection.”);
});
```
// Find All Documents
```javascript
const collection = db.collection(‘documents’);
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
console.log(“Found the following records”);
console.log(docs);
});
```
// Update a document
```
const collection = db.collection(‘documents’);
collection.updateOne({ a : 2 }, { $set: { b : 1 } }, function(err, result) {
assert.equal(err, null);
console.log(“Updated the document with the field a equal to 2”);
});
```
// Remove Document
```
const collection = db.collection(‘documents’);
collection.deleteOne({ a : 3 }, function(err, result) {
assert.equal(err, null);
console.log(“Removed the document with the field a equal to 3”);
});
```
Above are the common operations you would use to perform CRUD operations on your MongoDB using Node.js.