如何更新 MongoDB 数据库中的子对象?


要更新子对象,请在 MongoDB 中使用 $set。让我们先创建一个包含文档的集合 −

>db.demo21.insertOne({"StudentId":"STU-101","StudentDetails":{"StudentName":"Chris","StudentAge":21}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14be8922d07d3b95082e6f")
}

使用 find() 方法显示集合中的所有文档 −

> db.demo21.find().pretty();

这将产生以下输出 −

{
   "_id" : ObjectId("5e14be8922d07d3b95082e6f"),
   "StudentId" : "STU-101",
   "StudentDetails" : {
      "StudentName" : "Chris",
      "StudentAge" : 21
   }
}

以下是更新 MongoDB 中子对象的查询 −

> db.demo21.update({"StudentId":'STU-101'},{$set:{'StudentDetails.StudentName':'Robert'}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

使用 find() 方法显示集合中的所有文档 −

> db.demo21.find().pretty();

这将产生以下输出 −

{
   "_id" : ObjectId("5e14be8922d07d3b95082e6f"),
   "StudentId" : "STU-101",
   "StudentDetails" : {
      "StudentName" : "Robert",
      "StudentAge" : 21
   }
}

更新于: 2020 年 4 月 1 日

242 浏览

启动你的 职业生涯

通过完成课程获取认证

开始
广告
© . All rights reserved.