๐ 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
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",
}
]);
๐ 2. Delete all the reviews for bookId
"0786222727" through a single command.โ
Answer
db.reviews.deleteMany({"bookId": "0786222727"})