在 MongoDB 中,如何向数组中的嵌入文档添加字段?

mongodbdatabasebig data analytics更新于 2026/1/12 14:07:17

您可以使用 update() 和 $ 运算符来实现此目的。首先,我们创建一个包含文档的集合。 −

> db.addAFieldDemo.insertOne(
...   {
...
...      "ClientName" : "Larry",
...      "ClientCountryName" : "US",
...      "ClientOtherDetails" : [
...         {
...            "ClientProjectName":"Online Banking System"
...         }
...      ]
...   }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd44bdc2cba06f46efe9ee8")
}

以下是使用 find() 方法显示集合中的所有文档的查询 −

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

这将产生以下输出 −

{
   "_id" : ObjectId("5cd44bdc2cba06f46efe9ee8"),
   "ClientName" : "Larry",
   "ClientCountryName" : "US",
   "ClientOtherDetails" : [
      {
         "ClientProjectName" : "Online Banking System"
      }
   ]
}

以下是向数组中的嵌入文档添加字段的查询 −

> db.addAFieldDemo.update({ClientOtherDetails:{$elemMatch:{"ClientProjectName" : "Online Banking System"}}},
... {$set :{'ClientOtherDetails.$.isMarried':true}},true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

让我们显示上述集合中的所有文档 −

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

这将产生以下输出 −

{
   "_id" : ObjectId("5cd44bdc2cba06f46efe9ee8"),
   "ClientName" : "Larry",
   "ClientCountryName" : "US",
   "ClientOtherDetails" : [
      {
         "ClientProjectName" : "Online Banking System",
         "isMarried" : true
      }
   ]
}

相关文章