如何更新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()method的帮助下显示集合中的所有文档。查询如下-

> 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"
}

这是更新所有文档的查询。“ StudentName”更新为“ StudentFirstName”-

> 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"
}