To add or update a new talk in the embedded document, you can use any of the atomic update operators depending on how many documents in the collection
you want to update. For a single atomic update, use the updateOne() method as in the following example:
1. Adding a new subdocument
// Example of adding a subdocument to an existing document.
var MongoClient = require('mongodb').MongoClient,
ObjectId = require('mongodb').ObjectId;
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
// Get a collection
var collection = db.collection('mycollection');
// The new talk document to be added
var doc = {
"id": "4",
"title": "PyData",
"speaker": {
"id": "7",
"name": "alice bob",
"about": "about the speaker",
"photo": "https://pbs.twimg.com/dUy_ueY2.jpeg"
}
};
// Update the document with an atomic operator
collection.updateOne(
{ "_id": ObjectId("58286e49769e3729e895d239") },
{ "$push": { "talks": doc } },
function(err, result){
console.log(result);
db.close();
}
)
});
In the above, you use the $push operator to append the specified document to an array of embedded documents (talks field).
2. Updating an existing subdocument
// Example of updating an existing subdocument.
var MongoClient = require('mongodb').MongoClient,
ObjectId = require('mongodb').ObjectId;
MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
// Get a collection
var collection = db.collection('mycollection');
// Update the document with an atomic operator
collection.updateOne(
{
"_id": ObjectId("58286e49769e3729e895d239"),
"talk.id": "3"
},
{ "$set": {
"talks.$.title": "Android version 7.0",
"talks.$.speaker.name": "foo bar"
} },
function(err, result){
console.log(result);
db.close();
}
)
});
With an existing document update, you apply the $set operator together with the $ positional operator in your update operation to change the embedded document fields. The $ positional operator will identify the correct element in the array to update without explicitly specifying the position of the element in the array. For this to work, the array field must appear as part of the query document, hence the query
{
"_id": ObjectId("58286e49769e3729e895d239"),
"talk.id": "3" // <-- array field is part of the query
}