【发布时间】:2021-10-04 14:48:18
【问题描述】:
我需要编写一个脚本,将新字段写入我的集合中的嵌入对象。 假设我的集合名称是 Proposition,它包含 100000 个文档,它看起来像这样:
[{
"Id": "1111",
"name":"Name",
"products": [
{
"productId": "P1",
},{
"productId": "P2",
}]
}]
我的目标是为每个产品添加一个名为 parent 的新字段:
[{
"Id": "1111",
"name":"Name",
"products": [
{
"productId": "P1",
**"parent": "parent1"**
},{
"productId": "P2",
**"parent": "Parent2"**
}]
}]
我需要从另一个名为 Products 的集合中获取父字段,看起来像这样
[{
"productId": "P1",
"parent": "parent1"
},
{
"productId": "P2",
"parent": "Parent2"
}]
因此脚本需要从 Product 集合中获取 productId 和与之相关的父级,然后通过添加父字段来更新包含该产品的命题集合。
我为知道而编写的脚本:
db.Products.find()
.toArray()
.forEach(function(product){
updateWithParentID(product.productId,product.parent)
})
function updateWithParentID(prosuctId,parent){
db.Propositions.updateOne(
{'products.productId':prosuctId},
{$set:{"products.$.parent":parent}})
}
它可以工作,但不幸的是它需要很多时间,所以我想知道是否有更好更有效的方法来执行此更新
谢谢。
【问题讨论】:
-
我建议使用批量写入操作以获得更好的性能。此外,对于您的更新,您需要掌握使用 arrayFilters 进行有针对性的更新,以便将您的详细信息嵌入到提案集合中。
标签: database mongodb mongoose nosql mongo-shell