Debug School

rakesh kumar
rakesh kumar

Posted on

Mongo Db commands

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
Enter fullscreen mode Exit fullscreen mode

show dbs: Lists all available databases.

show dbs
Enter fullscreen mode Exit fullscreen mode

db.createCollection: Creates a new collection.

db.createCollection("users")
Enter fullscreen mode Exit fullscreen mode

db.dropDatabase: Deletes the current database.

db.dropDatabase()
Enter fullscreen mode Exit fullscreen mode

Collection Operations:

db.collection.insertOne: Inserts a document into a collection.

db.users.insertOne({ name: "John", age: 30 })
Enter fullscreen mode Exit fullscreen mode

db.collection.insertMany: Inserts multiple documents into a collection.

db.users.insertMany([
  { name: "John", age: 30 },
  { name: "Alice", age: 25 },
  { name: "Bob", age: 35 }
])
Enter fullscreen mode Exit fullscreen mode

db.collection.find: Retrieves documents from a collection.

db.users.find()
Enter fullscreen mode Exit fullscreen mode

db.collection.findOne: Retrieves a single document from a collection.

db.users.findOne({ name: "John" })
Enter fullscreen mode Exit fullscreen mode

db.collection.updateOne: Updates a single document in a collection.

db.users.updateOne({ name: "John" }, { $set: { age: 32 } })
Enter fullscreen mode Exit fullscreen mode

db.collection.updateMany: Updates multiple documents in a collection.

db.users.updateMany({ age: { $gte: 30 } }, { $inc: { age: 1 } })
Enter fullscreen mode Exit fullscreen mode

db.collection.deleteOne: Deletes a single document from a collection.

db.users.deleteOne({ name: "John" })
Enter fullscreen mode Exit fullscreen mode

db.collection.deleteMany: Deletes multiple documents from a collection.

db.users.deleteMany({ age: { $gte: 30 } })
Enter fullscreen mode Exit fullscreen mode

db.collection.aggregate: Performs aggregation operations on a collection.

db.users.aggregate([
  { $match: { age: { $gte: 25 } } },
  { $group: { _id: "$age", count: { $sum: 1 } } }
])
Enter fullscreen mode Exit fullscreen mode

db.collection.drop: Deletes a collection.

db.users.drop()
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

Image description

Image description

Image description

Top comments (0)