Mongodb 聚合子数组中的更新字段
Mongodb aggregate update field in sub array
首先,我使用的是 AWS 的 DocumentDB,所以我没有使用所有 MongoDB 函数。
我有这些记录:
{
"_id" : ObjectId("609be32555c7753b0cb21fsd"),
"validaProdutos" : [
{
"atributos" : [
{
"codigo" : "seller",
"valores" : []
}
]
}
],
},
{
"_id" : ObjectId("609be32555c7753b0cb20edc"),
"validaProdutos" : [
{
"atributos" : [
{
"codigo" : "brand",
"valores" : []
}
]
}
],
},
{
"_id" : ObjectId("609be32555c7753b0cb32123"),
"validaProdutos" : [
{
"atributos" : [
{
"codigo" : "seller",
"valores" : []
}
]
}
],
}
当 validaProdutos.atributos.codigo === “卖家”
时,我需要将 validaProdutos.atributos.codigo 更新为“完成”
我尝试了很多东西,但最后一次尝试是:
db.col1.aggregate([
{
"$addFields": {
"validaProdutos.atributos": {
$filter: {
input: "$validaProdutos.atributos",
as: "item",
cond: [{ $eq: ["$$item.codigo", "seller"] }, "done", "$$item.codigo"]
}
}
},
{ $out: "col1" }
},
])
但是不行,只是获取一个未修改的列表。
有人帮忙吗?
您应该使用带有 arrayFilters 和 multi 等于 true 的 update
方法,以影响您集合中的所有文档:
https://mongoplayground.net/p/Ln2qMCm9GMB
db.collection.update(
{},
{
$set: {
"validaProdutos.$[].atributos.$[a].codigo": "done",
},
},
{
multi: true,
arrayFilters: [
{
"a.codigo": "seller",
},
],
}
);
首先,我使用的是 AWS 的 DocumentDB,所以我没有使用所有 MongoDB 函数。
我有这些记录:
{
"_id" : ObjectId("609be32555c7753b0cb21fsd"),
"validaProdutos" : [
{
"atributos" : [
{
"codigo" : "seller",
"valores" : []
}
]
}
],
},
{
"_id" : ObjectId("609be32555c7753b0cb20edc"),
"validaProdutos" : [
{
"atributos" : [
{
"codigo" : "brand",
"valores" : []
}
]
}
],
},
{
"_id" : ObjectId("609be32555c7753b0cb32123"),
"validaProdutos" : [
{
"atributos" : [
{
"codigo" : "seller",
"valores" : []
}
]
}
],
}
当 validaProdutos.atributos.codigo === “卖家”
时,我需要将 validaProdutos.atributos.codigo 更新为“完成”我尝试了很多东西,但最后一次尝试是:
db.col1.aggregate([
{
"$addFields": {
"validaProdutos.atributos": {
$filter: {
input: "$validaProdutos.atributos",
as: "item",
cond: [{ $eq: ["$$item.codigo", "seller"] }, "done", "$$item.codigo"]
}
}
},
{ $out: "col1" }
},
])
但是不行,只是获取一个未修改的列表。
有人帮忙吗?
您应该使用带有 arrayFilters 和 multi 等于 true 的 update
方法,以影响您集合中的所有文档:
https://mongoplayground.net/p/Ln2qMCm9GMB
db.collection.update(
{},
{
$set: {
"validaProdutos.$[].atributos.$[a].codigo": "done",
},
},
{
multi: true,
arrayFilters: [
{
"a.codigo": "seller",
},
],
}
);