如何在 MongoDB 中更新所有文档?


你可以使用 updateMany() 来更新文档。我们创建一个包含文档的集合。创建包含文档的集合的查询如下 −

> db.updateManyDocumentsDemo.insertOne({"StudentName":"John","StudentLastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c948edd4cf1f7a64fa4df48")
}
> db.updateManyDocumentsDemo.insertOne({"StudentName":"John","StudentLastName":"Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c948ee64cf1f7a64fa4df49")
}
> db.updateManyDocumentsDemo.insertOne({"StudentName":"Carol","StudentLastName":"Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c948ef14cf1f7a64fa4df4a")
}
> db.updateManyDocumentsDemo.insertOne({"StudentName":"David","StudentLastName":"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c948f044cf1f7a64fa4df4b")
}

使用 find() 方法显示集合中的所有文档。查询如下 −

> db.updateManyDocumentsDemo.find().pretty();

输出如下 −

{
   "_id" : ObjectId("5c948edd4cf1f7a64fa4df48"),
   "StudentName" : "John",
   "StudentLastName" : "Smith"
}
{
   "_id" : ObjectId("5c948ee64cf1f7a64fa4df49"),
   "StudentName" : "John",
   "StudentLastName" : "Doe"
}
{
   "_id" : ObjectId("5c948ef14cf1f7a64fa4df4a"),
   "StudentName" : "Carol",
   "StudentLastName" : "Taylor"
}
{
   "_id" : ObjectId("5c948f044cf1f7a64fa4df4b"),
   "StudentName" : "David",
   "StudentLastName" : "Miller"
}

以下是对所有文档进行更新的查询。用 “StudentFirstName” 更新 “StudentName” −

> db.updateManyDocumentsDemo.updateMany({}, {$rename: {'StudentName': "StudentFirstName"}});

输出如下 −

{ "acknowledged" : true, "matchedCount" : 4, "modifiedCount" : 4 }

检查文档是否已被更新。查询如下 −

> db.updateManyDocumentsDemo.find().pretty();

输出如下 −

{
   "_id" : ObjectId("5c948edd4cf1f7a64fa4df48"),
   "StudentLastName" : "Smith",
   "StudentFirstName" : "John"
}
{
   "_id" : ObjectId("5c948ee64cf1f7a64fa4df49"),
   "StudentLastName" : "Doe",
   "StudentFirstName" : "John"
}
{
   "_id" : ObjectId("5c948ef14cf1f7a64fa4df4a"),
   "StudentLastName" : "Taylor",
   "StudentFirstName" : "Carol"
}
{
   "_id" : ObjectId("5c948f044cf1f7a64fa4df4b"),
   "StudentLastName" : "Miller",
   "StudentFirstName" : "David"
}

更新日期:2019-07-30

734 次浏览

助力你的职业生涯

获取认证,完成课程

开始
广告