如何在 MongoDB 中向现有记录添加字段?
可以使用 update 指令向现有记录添加字段。让我们首先创建一个包含文档的集合 -
> db.addAFieldToEveryRecordDemo.insertOne({"ClientName":"Chris","ClientAge":34}); { "acknowledged" : true, "insertedId" : ObjectId("5cd00e32588d4a6447b2e061") } > db.addAFieldToEveryRecordDemo.insertOne({"ClientName":"Robert","ClientAge":36}); { "acknowledged" : true, "insertedId" : ObjectId("5cd00e59588d4a6447b2e062") }
以下是要在 find() 方法的帮助下从集合中显示所有文档的查询 -
> db.addAFieldToEveryRecordDemo.find().pretty();
将会产生以下输出 -
{ "_id" : ObjectId("5cd00e32588d4a6447b2e061"), "ClientName" : "Chris", "ClientAge" : 34 } { "_id" : ObjectId("5cd00e59588d4a6447b2e062"), "ClientName" : "Robert", "ClientAge" : 36 }
以下是向每条记录添加字段的查询。我们要添加 ClientDetails -
>db.addAFieldToEveryRecordDemo.update({},{$set:{"ClientDetails.ClientCountryName":""}},true,true); WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
让我们检查所有文档是否已添加了新记录 -
> db.addAFieldToEveryRecordDemo.find().pretty();
将会产生以下输出 -
{ "_id" : ObjectId("5cd00e32588d4a6447b2e061"), "ClientName" : "Chris", "ClientAge" : 34, "ClientDetails" : { "ClientCountryName" : "" } } { "_id" : ObjectId("5cd00e59588d4a6447b2e062"), "ClientName" : "Robert", "ClientAge" : 36, "ClientDetails" : { "ClientCountryName" : "" } }
广告