Ad Code

Responsive Advertisement

✨ MongoDB - CRUD

1. CRUD Operations in MongoDB



CRUD stands for Create, Read, Update, and Delete, the four basic operations for managing data in any database. MongoDB provides powerful methods for performing these actions on collections and documents.

1.1 Create (Insert)

insertOne(): Inserts a single document into a collection.

Syntax: db.collection.insertOne(<document>)

Example:

db.collection.insertOne({ name: "Alice", age: 25 })
  

insertMany(): Inserts multiple documents into a collection.

Syntax: db.collection.insertMany([<doc1>, <doc2>, ...])

Example:

db.collection.insertMany([
  { name: "Bob", age: 30 },
  { name: "Charlie", age: 35 }
])
  

1.2 Read (Query)

find(): Retrieves documents that match a filter. If no filter is provided, all documents are returned.

Syntax: db.collection.find(<query>, <projection>)

Example – Fetch all documents:

db.collection.find({})
  

Example – Fetch documents with age greater than 25:

db.collection.find({ age: { $gt: 25 } })
  

findOne(): Retrieves the first document matching the criteria.

Syntax: db.collection.findOne(<query>, <projection>)

Example:

db.collection.findOne({ name: "Alice" })
  

1.3 Update

updateOne(): Updates the first document matching the filter.

Syntax: db.collection.updateOne(<filter>, <update>, <options>)

Example:

db.collection.updateOne({ name: "Alice" }, { $set: { age: 26 } })
  

updateMany(): Updates all documents that match the filter.

Syntax: db.collection.updateMany(<filter>, <update>, <options>)

Example – Increase age by 1 where age < 30:

db.collection.updateMany({ age: { $lt: 30 } }, { $inc: { age: 1 } })
  

1.4 Delete

deleteOne(): Deletes the first document matching the filter.

Syntax: db.collection.deleteOne(<filter>, <options>)

Example:

db.collection.deleteOne({ name: "Alice" })
  

deleteMany(): Deletes all documents matching the filter.

Syntax: db.collection.deleteMany(<filter>, <options>)

Example – Delete all users with age greater than 30:

db.collection.deleteMany({ age: { $gt: 30 } })

1.5 Rename Collection

renameCollection():Renames collection.

Syntax: db.collection.renameCollection("New Name")

Example – Rename the collection to new

db.collection.renameCollection("New")
  

Post a Comment

0 Comments