MongoDB
| Created | |
|---|---|
| Type | Database |
| Language | NoSQL |
| Last Edit |
Installation & Setup
Run MongoDB Server: Mac & Linux
Example: /Users/ashirali-mg/Programs/mongodb-6.0.2/bin/mongod --dbpath=/Users/ashirali-mg/Documents/mongodb-data
mongod-filepath --dbpath=db-folderMongoDB Admin
Robo 3T
MongoDB With Node
Quick Start
This guide shows you how to create an application that uses the MongoDB Node.js driver to connect to a MongoDB cluster hosted on MongoDB Atlas. If you prefer to connect to MongoDB using a different driver or programming language, see our list of official drivers.

💡
Default Port: 27017
Install
npm install mongodbConnect
const { MongoClient } = require("mongodb");
// Connection URI
const uri = "mongodb://localhost:27017";
// Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Establish and verify connection
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);Insert
Single Document
Insert data to a particular collection (tables in NoSQL)
💡
If no database with given name is present, MongoDB will create one.
import { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function run() {
try {
const database = client.db("insertDB");
const haiku = database.collection("haiku");
// create a document to insert
const doc = {
title: "Record of a Shriveled Datum",
content: "No bytes, no problem. Just insert a document, in MongoDB",
}
const result = await haiku.insertOne(doc);
console.log(`A document was inserted with the _id: ${result.insertedId}`);
} finally {
await client.close();
}
}
run().catch(console.dir);Multiple Documents
const docs = [
{ name: "cake", healthy: false },
{ name: "lettuce", healthy: true },
{ name: "donut", healthy: false }
];
// this option prevents additional documents from being inserted if one fails
const options = { ordered: true };
const result = await foods.insertMany(docs, options);
console.log(`${result.insertedCount} documents were inserted`);Object ID
const { ObjectId } = require("mongodb");
const id = new ObjectId();Is made of:
- A 4-byte timestamp, representing the ObjectId's creation, measured in seconds since the Unix epoch.
- A 5-byte random value generated once per process. This random value is unique to the machine and process.
- A 3-byte incrementing counter, initialized to a random value.
Get Timestamp when ID is created
console.log(id.getTimestamp());await userCollection.insertOne({
_id: id,
name: "TestName with id",
age: 20,
});Set ID during Insert
Read
Read Single Document
const database = client.db("task-manager");
const userCollection = database.collection("users");
const user = await userCollection.findOne({ name: "Bukowski" });
console.log({ user });Read with ID
const user = await userCollection.findOne({
_id: new ObjectId("6353af602e35bf22c12015e9"),
});Read Multiple Documents
const query = { age: { $gt: 20 } }; //find users with age greater than 20
const cursor = await userCollection.find(query);
await cursor.forEach((user) => console.log(user));Count Documents With Query
userCollection.countDocuments(query).then((count) => {
console.log(count);
});Update
Update Operators
$set- replaces the value of a field with a specified one
$inc- increments or decrements field values
$rename- renames fields
$unset- removes fields
$mul- multiplies a field value by a specified number
Update Single Document
const filter = { _id: new ObjectId("6353c26540b9a601c01789c6") };
const query = {
$set: {
name: "Updated Name",
},
};
const result = await userCollection.updateOne(filter, query);
console.log(result);Update Multiple Documents
const filter = { completed: false };
const query = {
$set: {
completed: true,
},
};
const result = await tasksCollection.updateMany(filter, query);Delete
Delete Single Document
const filter = { age: 20 };
const result = await userCollection.deleteOne(filter);
if (result.deletedCount === 1) {
console.log("Successfully deleted one document.");
} else {
console.log("No documents matched the query. Deleted 0 documents.");
}Delete Multiple Documents
const filter = { age: 20 };
const result = await userCollection.deleteMany(filter);
console.log("Deleted " + result.deletedCount + " documents");