为此,只需使用update()进行更新。让我们创建一个包含文档的集合-
> db.dem0143.insertOne({"StudentId":1,"Details":{"Name":"Chris"}}); { "acknowledged" : true, "insertedId" : ObjectId("5e32eb9efdf09dd6d08539b7") } > db.dem0143.insertOne({"StudentId":2,"Details":{"Name":"David"}}); { "acknowledged" : true, "insertedId" : ObjectId("5e32eba5fdf09dd6d08539b8") }
在find()方法的帮助下显示集合中的所有文档-
> db.dem0143.find();
这将产生以下输出-
{ "_id" : ObjectId("5e32eb9efdf09dd6d08539b7"), "StudentId" : 1, "Details" : { "Name" : "Chris" } } { "_id" : ObjectId("5e32eba5fdf09dd6d08539b8"), "StudentId" : 2, "Details" : { "Name" : "David" } }
以下是在单个更新中实现$set和$push的查询-
> db.dem0143.update({_id: ObjectId("5e32eba5fdf09dd6d08539b8")}, {$push: {StudentAge:21}, $set: {"Details.Name":"John Doe"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()方法的帮助下显示集合中的所有文档-
> db.dem0143.find();
这将产生以下输出-
{ "_id" : ObjectId("5e32eb9efdf09dd6d08539b7"), "StudentId" : 1, "Details" : { "Name" : "Chris" } } { "_id" : ObjectId("5e32eba5fdf09dd6d08539b8"), "StudentId" : 2, "Details" : { "Name" : "John Doe" }, "StudentAge" : [ 21 ] }