您可以将update命令与forEach()一起使用以进行大集合。首先让我们创建一个包含文档的集合
>db.addingNewPropertyDemo.insertOne({"StudentName":"John","StudentAge":23,"CountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5ca1e61866324ffac2a7dc56") } >db.addingNewPropertyDemo.insertOne({"StudentName":"David","StudentAge":21,"CountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5ca1e62366324ffac2a7dc57") } >db.addingNewPropertyDemo.insertOne({"StudentName":"Bob","StudentAge":21,"CountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5ca1e62d66324ffac2a7dc58") }
以下是查询以借助find()方法显示集合中的所有文档
> db.addingNewPropertyDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5ca1e61866324ffac2a7dc56"), "StudentName" : "John", "StudentAge" : 23, "CountryName" : "US" } { "_id" : ObjectId("5ca1e62366324ffac2a7dc57"), "StudentName" : "David", "StudentAge" : 21, "CountryName" : "AUS" } { "_id" : ObjectId("5ca1e62d66324ffac2a7dc58"), "StudentName" : "Bob", "StudentAge" : 21, "CountryName" : "UK" }
以下是向大型集合中的每个文档添加新属性的查询
> db.addingNewPropertyDemo.find().forEach(function(data){ db.addingNewPropertyDemo.update({_id: data._id}, {$set: { StudentNameInUpperCase: data.StudentName.toUpperCase() }}) });
让我们检查是否添加了新属性
> db.addingNewPropertyDemo.find().pretty();
以下是显示新属性的输出
{ "_id" : ObjectId("5ca1e61866324ffac2a7dc56"), "StudentName" : "John", "StudentAge" : 23, "CountryName" : "US", "StudentNameInUpperCase" : "JOHN" } { "_id" : ObjectId("5ca1e62366324ffac2a7dc57"), "StudentName" : "David", "StudentAge" : 21, "CountryName" : "AUS", "StudentNameInUpperCase" : "DAVID" } { "_id" : ObjectId("5ca1e62d66324ffac2a7dc58"), "StudentName" : "Bob", "StudentAge" : 21, "CountryName" : "UK", "StudentNameInUpperCase" : "BOB" }
查看上面的示例输出,添加了StudentNameInUpperCase属性。