HOWTO · MongoDB
使用 forEach() 更新 MongoDB Shell 中的数组字段
本教程演示了如何使用 forEach() 更新 MongoDB shell 中的数组字段。
本页内容
今天,我们将学习如何在使用 MongoDB shell 时使用 forEach() 来更新数组字段。
使用 forEach() 更新 MongoDB Shell 中的数组字段
要使用 forEach(),让我们准备一个名为 collection 的样本集合,其中包含两个文档。你也可以使用下面的查询来继续我们的工作。
示例代码:
> use updateArrayField
> db.createCollection('collection');
> db.collection.insertMany([
{
"name": "Mehvish",
"gender": "Female",
"fields" : [
{ "_id" : 1, "items" : [ 1,3,4,5,6,7 ] }
]
},
{
"name": "Thomas Christopher",
"gender": "Male",
"fields" : [
{ "_id" : 1, "items" : [ 1,3,4,5,6,7 ] }
]
}
]);
接下来,我们使用这些文档来更新名为 fields.items 的数组字段
"items" : [ 1,3,4,5,6,7]
至
"items" : [
{item: 1, key: 0},
{item: 3, key: 0},
{item: 4, key: 0},
{item: 5, key: 0},
{item: 6, key: 0},
{item: 7, key: 0}
]
为此,我们可以使用嵌套的 forEach(),如下所示。
示例代码:
> var table = db.collection.find();
> table.forEach(function( oneRow ) {
var newFields = [];
oneRow.fields.forEach( function( oneField ){
var newItems = [];
oneField.items.forEach( function( item ){
var aNewItem = { item: parseInt(item), key: 0 };
newItems.push( aNewItem );
} );
newFields.push({ _id: oneField._id, items: newItems });
} )
db.collection.update(
{ _id: oneRow._id },
{ "$set": { "fields": newFields } }
);
});
在 mongo shell 上执行以下查询以查看更新的文档。
示例代码:
> db.collection.find()
输出:
{
"_id" : ObjectId("62a708054eb9c63e48daeba4"),
"name" : "Mehvish",
"gender" : "Female",
"fields" : [
{
"_id" : 1,
"items" : [
{ "item" : 1, "key" : 0 },
{ "item" : 3, "key" : 0 },
{ "item" : 4, "key" : 0 },
{ "item" : 5, "key" : 0 },
{ "item" : 6, "key" : 0 },
{ "item" : 7, "key" : 0 }
]
}
]
}
{
"_id" : ObjectId("62a708054eb9c63e48daeba5"),
"name" : "Thomas Christopher",
"gender" : "Male",
"fields" : [
{
"_id" : 1,
"items" : [
{ "item" : 1, "key" : 0 },
{ "item" : 3, "key" : 0 },
{ "item" : 4, "key" : 0 },
{ "item" : 5, "key" : 0 },
{ "item" : 6, "key" : 0 },
{ "item" : 7, "key" : 0 }
]
}
]
}
为了获得上述输出,我们从 collection 中读取所有数据并使用 forEach() 迭代 collection 的每个文档。接下来,我们使用另一个 forEach() 来遍历指定文档的每个字段。
然后,第三个 forEach() 用于迭代 collection 中 fields.items 字段的值。我们使用每个值来形成所需的更新并将其保存到 aNewItem 变量中,该变量使用 push() 方法进一步插入 newItems 数组中。
之后,我们使用 oneField._id 和 newItems 数组创建一个文档,将其推入 newFields 数组,该数组进一步用于更新 collection。