要追加子文档,请在MongoDB中使用$push。update()用于更新。让我们创建一个包含文档的集合-
> db.demo587.insertOne({"id":101,"details":[{Name:"Chris",Age:21,Marks:57}]});{ "acknowledged" : true, "insertedId" : ObjectId("5e92ba01fd2d90c177b5bcc9") } > db.demo587.insertOne({"id":102,"details":[{Name:"Bob",Age:22,Marks:78}]});{ "acknowledged" : true, "insertedId" : ObjectId("5e92ba0efd2d90c177b5bcca") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo587.find();
这将产生以下输出-
{ "_id" : ObjectId("5e92ba01fd2d90c177b5bcc9"), "id" : 101, "details" : [ { "Name" : "Chris", "Age" : 21, "Marks" : 57 } ] } { "_id" : ObjectId("5e92ba0efd2d90c177b5bcca"), "id" : 102, "details" : [ { "Name" : "Bob", "Age" : 22, "Marks" : 78 } ] }
以下是在MongoDB中保持追加子文档的查询-
> db.demo587.update({"id":101}, {"$push": {"details":{Subject:"MongoDB"}}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()方法的帮助下显示集合中的所有文档-
> db.demo587.find();
这将产生以下输出-
{ "_id" : ObjectId("5e92ba01fd2d90c177b5bcc9"), "id" : 101, "details" : [ { "Name" : "Chris", "Age" : 21, "Marks" : 57 }, { "Subject" : "MongoDB" } ] } { "_id" : ObjectId("5e92ba0efd2d90c177b5bcca"), "id" : 102, "details" : [ { "Name" : "Bob", "Age" : 22, "Marks" : 78 } ] }