{
"_id": "659e76b929be316e566cdc36",
"main_array": [
{
"_id": "659e76b929be316e566cdc39",
"sub_array": [
[
{
"_id": "659e76b929be316e566cdc3c",
"info": {
"_id": "654b725918297c74977025da",
"title": "Cycling"
},
// Other fields
},
{
"_id": "659e76b929be316e566cdc3e",
"info": {
"_id": "654b717718297c74977025c6",
"title": "Running"
},
// Other fields
}
],
[
{
"_id": "659e76b929be316e566cdc42",
"info": {
"_id": "654b725918297c74977025da",
"title": "Cycling"
},
// Other fields
}
]
]
}
]
}
这就是我目前正在为我的项目开发的结构。
我需要什么:
我需要更新
title
字段,其中 info._id
字段与 given_id
匹配。
我尝试过的:
我尝试过多次这样的查询
await MyModel.updateMany(
{},
{
$set: {
"main_array.$[].sub_array.$[].$[inner].info.title": new_title
},
},
{
arrayFilters: [
{ "inner.info._id": given_id },
],
}
);
或
await MyModel.updateMany(
{},
{
$set: {
"main_array.$[].sub_array.$[inner].info.title": new_title
},
},
{
arrayFilters: [
{ "inner.info._id": given_id },
],
}
);
或
await MyModel.updateMany(
{"main_array.sub_array.info._id": given_id},
{
$set: {
"main_array.$[].sub_array.$[inner].info.title": new_title
},
},
{
arrayFilters: [
{ "inner.info._id": given_id },
],
}
);
经过大量研究后,我发现了更多组合,但无法弄清楚。互联网上的所有解决方案都是关于对象的嵌套数组,但就我而言,我有一个对象数组的数组,这是主要问题。任何帮助将不胜感激
MongoDb 游乐场链接 :https://mongoplayground.net/p/XCv1tjq9rGx
Below aggregation is also provided:
{
"_id": "659e76b929be316e566cdc36",
"main_array": [
{
"_id": "659e76b929be316e566cdc39",
"sub_array": [
[
{
"_id": "659e76b929be316e566cdc3c",
"info": {
"_id": "654b725918297c74977025da",
"title": "Cycling"
},
// Other fields
},
{
"_id": "659e76b929be316e566cdc3e",
"info": {
"_id": "654b717718297c74977025c6",
"title": "Running"
},
// Other fields
}
],
[
{
"_id": "659e76b929be316e566cdc42",
"info": {
"_id": "654b725918297c74977025da",
"title": "Cycling"
},
// Other fields
}
]
]
}
]
}
db.collection.update({},
{
$set: {
"main_array.$[].sub_array.$[].$[inner].info.title": "new_title"
}
},
{
arrayFilters: [
{
"inner._id": "659e76b929be316e566cdc3e"
}
]
})
[
{
"_id": "659e76b929be316e566cdc36",
"main_array": [
{
"_id": "659e76b929be316e566cdc39",
"sub_array": [
[
{
"_id": "659e76b929be316e566cdc3c",
"info": {
"_id": "654b725918297c74977025da",
"title": "Cycling"
}
},
{
"_id": "659e76b929be316e566cdc3e",
"info": {
"_id": "654b717718297c74977025c6",
"title": "new_title"
}
}
],
[
{
"_id": "659e76b929be316e566cdc42",
"info": {
"_id": "654b725918297c74977025da",
"title": "Cycling"
}
}
]
]
}
]
}
]