- Download the appropriate MongoDB package for your operating system.
- Extract the downloaded archive.
- Set environment variables for MongoDB_HOME and PATH.
- Start the MongoDB daemon service.
- Connect to the MongoDB shell using the
mongocommand.
- Use the
mongod --versioncommand to check the MongoDB version. - Use the
ps aux | grep mongodcommand to see if the mongod process is running.
By default, MongoDB listens on localhost (127.0.0.1) and port 27017.
- Create:
db.collectionName.insertOne(document)ordb.collectionName.insertMany(documents) - Read:
db.collectionName.find()ordb.collectionName.findOne() - Update:
db.collectionName.updateOne()ordb.collectionName.updateMany() - Delete:
db.collectionName.deleteOne()ordb.collectionName.deleteMany()
// Create
db.users.insertOne({ name: "John Doe", age: 30, city: "New York" });
db.products.insertMany([
{ name: "Product A", price: 19.99 },
{ name: "Product B", price: 29.99 },
{ name: "Product C", price: 9.99 }
]);
// Read
db.users.find().pretty(); // Find all documents
db.products.findOne({ price: { $gt: 20 } }); // Find one product with price greater than 20
// Update
db.users.updateOne({ name: "John Doe" }, { $set: { age: 31 } });
db.products.updateMany({ price: { $lt: 10 } }, { $inc: { price: 2 } });
// Delete
db.users.deleteOne({ name: "John Doe" });
db.products.deleteMany({ price: { $gt: 30 } });- find() returns an array of all documents matching the query, while
- findOne() returns only the first matching document.
- $set: Sets the value of a field to the specified value.
- $inc: Increments a numeric field by a specified value.
- $push: Adds one or more elements to an array.
A new database is created implicitly when you switch to it and insert data. For example:
use myNewDatabase
db.myCollection.insertOne({ name: "John Doe" })Use the replaceOne method to replace a document completely. For example, to replace a document with name John Doe:
db.collectionName.replaceOne(
{ name: "John Doe" },
{ name: "John Doe", age: 31, occupation: "Manager" }
)Use the show collections command in the MongoDB shell:
Use the createUser method. For example, to create a user dbUser with read and write permissions:
db.createUser({
user: "dbUser",
pwd: "password",
roles: [{ role: "readWrite", db: "myDatabase" }]
})