您可以使用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" : "" } }