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

mongodbdatabasebig data analytics更新于 2026/1/9 18:52:17

要更新子对象,请在 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
   }
}

相关文章