MongoDB provides a comprehensive set of commands for working with databases and collections. Here's a list of some commonly used MongoDB commands along with examples:
Database Operations:
use: Switches to a specified database.
use mydatabase
show dbs: Lists all available databases.
show dbs
db.createCollection: Creates a new collection.
db.createCollection("users")
db.dropDatabase: Deletes the current database.
db.dropDatabase()
Collection Operations:
db.collection.insertOne: Inserts a document into a collection.
db.users.insertOne({ name: "John", age: 30 })
db.collection.insertMany: Inserts multiple documents into a collection.
db.users.insertMany([
{ name: "John", age: 30 },
{ name: "Alice", age: 25 },
{ name: "Bob", age: 35 }
])
db.collection.find: Retrieves documents from a collection.
db.users.find()
db.collection.findOne: Retrieves a single document from a collection.
db.users.findOne({ name: "John" })
db.collection.updateOne: Updates a single document in a collection.
db.users.updateOne({ name: "John" }, { $set: { age: 32 } })
db.collection.updateMany: Updates multiple documents in a collection.
db.users.updateMany({ age: { $gte: 30 } }, { $inc: { age: 1 } })
db.collection.deleteOne: Deletes a single document from a collection.
db.users.deleteOne({ name: "John" })
db.collection.deleteMany: Deletes multiple documents from a collection.
db.users.deleteMany({ age: { $gte: 30 } })
db.collection.aggregate: Performs aggregation operations on a collection.
db.users.aggregate([
{ $match: { age: { $gte: 25 } } },
{ $group: { _id: "$age", count: { $sum: 1 } } }
])
db.collection.drop: Deletes a collection.
db.users.drop()
Top comments (0)