如何在大型 MongoDB 集合中为每个文档添加新属性?
mongodbdatabasebig data analytics更新于 2026/1/27 2:37:17
对于大型集合,您可以将 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 属性已添加。

