如何使用MongoDB在嵌套数组中添加新项目?
为此,请find()
与一起使用update()
。让我们创建一个包含文档的集合-
> db.demo124.insertOne( ... { ... "Name" : "John", ... "Id" : 101, ... "ProjectDetails" : [{ ... "ProjectName1" : "Online Book", ... "ProjectName2" : "Online Banking" ... }, { ... "ProjectName1" : "Online Library Management System", ... "ProjectName2" : "School Management System" ... }] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2f2c8b140daf4c2a3544bb") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo124.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2f2c8b140daf4c2a3544bb"), "Name" : "John", "Id" : 101, "ProjectDetails" : [ { "ProjectName1" : "Online Book", "ProjectName2" : "Online Banking" }, { "ProjectName1" : "Online Library Management System", "ProjectName2" : "School Management System" } ] }
以下是在嵌套数组中添加新项目的查询-
> db.demo124.find().toArray().forEach( ... function(d){ ... for(var i = 0; i< d.ProjectDetails.length; ++i) { ... d.ProjectDetails[i]['ProjectName3'] = 'Online Snake Game'; ... } ... db.demo124.update({_id: d._id}, d); ... } ... );
在find()
方法的帮助下显示集合中的所有文档-
> db.demo124.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e2f2c8b140daf4c2a3544bb"), "Name" : "John", "Id" : 101, "ProjectDetails" : [ { "ProjectName1" : "Online Book", "ProjectName2" : "Online Banking", "ProjectName3" : "Online Snake Game" }, { "ProjectName1" : "Online Library Management System", "ProjectName2" : "School Management System", "ProjectName3" : "Online Snake Game" } ] }