๐ INSERT โ insertOne() & DELETE โ deleteOne()
MongoDB provides two methods for inserting documents into a collection:
.insertOne(): Inserts a single document.insertMany(): Inserts multiple documents at once
And just like insert, MongoDB provides:
.deleteOne(): Deletes the first matching document..deleteMany(): Deletes all matching documents.
Example: Insert a new reviewโ
db.reviews.insertOne({
text: "Best book I have ever read.",
rating: 5,
name: "Jack",
bookId: "0786222727",
});
Equivalent SQL queryโ
INSERT INTO reviews (text, rating, name, bookId)
VALUES ('Best book I have ever read.', 5, 'Jack', '0786222727');
Example: Insert multiple reviewsโ
db.reviews.insertMany([
{
text: "Amazing plot.",
rating: 5,
name: "John",
bookId: "0786222727",
},
{
text: "Over-hyped, tbh I feel it's very boring!",
rating: 2,
name: "Nick",
bookId: "0786222727",
},
]);
Example: Delete one reviewโ
db.reviews.deleteOne({
bookId: "0786222727",
});
Equivalent SQL queryโ
DELETE FROM reviews WHERE bookId = '0786222727';
Challengeโ
๐ 1. Insert 4 more reviews for bookId "0786222727".โ
Answer
- JavaScript
- mongosh
- C#
const reviews = db.collection("reviews");
await reviews.insertMany([
{
text: "Thrilling end.",
rating: 4,
name: "Mark",
bookId: "0786222727",
},
{
text: "Must read!",
rating: 5,
name: "Raj",
bookId: "0786222727",
},
{
text: "Very expensive",
rating: 3,
name: "Yun",
bookId: "0786222727",
},
{
text: "Extremely satisfied with the storyline!",
rating: 5,
name: "Lisa",
bookId: "0786222727",
}
]);
db.reviews.insertMany([
{
text: "Thrilling end.",
rating: 4,
name: "Mark",
bookId: "0786222727",
},
{
text: "Must read!",
rating: 5,
name: "Raj",
bookId: "0786222727",
},
{
text: "Very expensive",
rating: 3,
name: "Yun",
bookId: "0786222727",
},
{
text: "Extremely satisfied with the storyline!",
rating: 5,
name: "Lisa",
bookId: "0786222727",
}
]);
var newReviews = new[]
{
new Review { Text = "Thrilling end.", Rating = 4, Name = "Mark", BookId = "0786222727" },
new Review { Text = "Must read!", Rating = 5, Name = "Raj", BookId = "0786222727" },
new Review { Text = "Very expensive", Rating = 3, Name = "Yun", BookId = "0786222727" },
new Review { Text = "Extremely satisfied with the storyline!", Rating = 5, Name = "Lisa", BookId = "0786222727" }
};
reviewsCollection.InsertMany(newReviews);
๐ 2. Delete all the reviews for bookId "0786222727" through a single command.โ
Answer
- JavaScript
- mongosh
- C#
const reviews = db.collection("reviews");
await reviews.deleteMany({"bookId": "0786222727"})
db.reviews.deleteMany({"bookId": "0786222727"})
IMongoCollection<Review> reviewsCollection = db.GetCollection<Review>("reviews");
var deletionResult = reviewsCollection.DeleteMany(r => r.BookId == "0786222727");
Console.WriteLine($"{deletionResult.DeletedCount} review(s) deleted.");