将新字段添加到 MongoDB 集合中的每个文档?
若要将新字段添加到 MongoDB 集合中的每个文档,可以使用 $set 运算符。语法如下
db.yourCollectionName.update({}, { $set: {"yourFieldName": yourValue} }, false, true);
为了解上述语法,我们使用一些文档创建一个集合。创建带有文档的集合的查询如下
>db.addNewFieldToEveryDocument.insertOne({"StudentName":"John","StudentAddress":"US "}); { "acknowledged" : true, "insertedId" : ObjectId("5c6efc0b6fd07954a48906ae") } >db.addNewFieldToEveryDocument.insertOne({"StudentName":"David","StudentAddress":"U K"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6efc0b6fd07954a48906af") } >db.addNewFieldToEveryDocument.insertOne({"StudentName":"Carol","StudentAddress":"U K"}); { "acknowledged" : true, "insertedId" : ObjectId("5c6efc0b6fd07954a48906b0") } >db.addNewFieldToEveryDocument.insertOne({"StudentName":"Bob","StudentAddress":"US" }); { "acknowledged" : true, "insertedId" : ObjectId("5c6efc0b6fd07954a48906b1") }
借助 find() 方法显示集合中的所有文档。查询如下
> db.addNewFieldToEveryDocument.find().pretty();
以下是输出
{ "_id" : ObjectId("5c6efc0b6fd07954a48906ae"), "StudentName" : "John", "StudentAddress" : "US" } { "_id" : ObjectId("5c6efc0b6fd07954a48906af"), "StudentName" : "David", "StudentAddress" : "UK" } { "_id" : ObjectId("5c6efc0b6fd07954a48906b0"), "StudentName" : "Carol", "StudentAddress" : "UK" } { "_id" : ObjectId("5c6efc0b6fd07954a48906b1"), "StudentName" : "Bob", "StudentAddress" : "US" }
以下是对每个文档添加新字段的查询
> db.addNewFieldToEveryDocument.update({}, { $set: {"StudentAge": 24} }, false, true); WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })
上面,我们已经在每个文档中添加了一个新字段 “StudentAge”:24。我们来查看字段 “StudentAge”:24 是否成功添加到每个文档。查询如下
> db.addNewFieldToEveryDocument.find().pretty();
以下是输出
{ "_id" : ObjectId("5c6efc0b6fd07954a48906ae"), "StudentName" : "John", "StudentAddress" : "US", "StudentAge" : 24 } { "_id" : ObjectId("5c6efc0b6fd07954a48906af"), "StudentName" : "David", "StudentAddress" : "UK", "StudentAge" : 24 } { "_id" : ObjectId("5c6efc0b6fd07954a48906b0"), "StudentName" : "Carol", "StudentAddress" : "UK", "StudentAge" : 24 } { "_id" : ObjectId("5c6efc0b6fd07954a48906b1"), "StudentName" : "Bob", "StudentAddress" : "US", "StudentAge" : 24 }
广告