将新属性添加到大量 MongoDB 集合中的每个文档?
对于大型集合,您可以将 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 属性。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP