Updating Embeded Documents
Add new element to array using $push operator
shop> db.comments.updateOne({_id:5}, {$push: {comments: {user: "Eva", text: "Subscribe"}}})
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
Remove last element from the array using $pop operator
shop> db.comments.updateOne({_id: 5}, {$pop: {'comments': 1}})
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
shop>
Update the emdedded documents usinh $ or positional operator
shop> db.comments.updateOne({_id: 7, 'comments.user': 'Alice'}, {$set: {'comments.$.text': "Awesome Prabin"}})
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
shop> db.comments.find({_id: 7})
[
{
_id: 7,
title: 'Introduction to MongoDB',
content: 'MongoDB is a popular NoSQL database...',
author: 'Vinod Thapa',
comments: [
{ user: 'Alice', text: 'Awesome Prabin' },
{ user: 'Vinod', text: 'Thanks for sharing.' }
],
metadata: { views: 1000, likes: 70 },
status: false
}
]