要在嵌入文档中添加或更新新的talk,您可以使用任何原子update operators,具体取决于集合中的文档数量
你想更新。对于单个原子更新,请使用 updateOne() 方法,如下例所示:
1.添加新的子文档
// 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();
}
)
});
在上面,您使用 $push 运算符将指定文档附加到嵌入文档数组(talks 字段)。
2。更新现有子文档
// 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();
}
)
});
对于现有的文档更新,您可以在更新操作中应用 $set 运算符和 $ positional operator 来更改嵌入的文档字段。 $ positional operator 将识别数组中要更新的正确元素,而无需显式指定数组中元素的位置。为此,数组字段必须作为查询文档的一部分出现,因此查询
{
"_id": ObjectId("58286e49769e3729e895d239"),
"talk.id": "3" // <-- array field is part of the query
}