首页 > 解决方案 > 如何在 MongoDB 聚合中替换数组的值?

问题描述

我试图仅在聚合结果中替换值,而不是在存储的文档中,这就是我使用聚合而不是更新的原因。

假设这些是存储在集合中的文档:

{ "_id": 1, "first_name": "foo1", items: [
        { "item": "gloves", "body": "hands" },
        { "item": "gloves", "body": "hands" },
        { "item": "shirts" , "body": "torso" }
    ]
},
{ "_id": 2, "first_name": "foo2", items: [
        { "item": "skirts", "where": "legs" },
        { "item": "jeans", "body": "legs" },
        { "item": "socks" , "body": "feet" },
        { "item": "gloves" , "body": "hands" }
    ]
},
{ "_id": 3, "first_name": "foo3", items: [
        { "item": "jacket", "where": "torso" },
        { "item": "socks", "body": "feet" },
        { "item": "shirts" , "body": "torso" }
    ]
}

聚合必须用“sandals”代替“gloves”,并将“body”从“hands”改为“feet”。预期结果是:

{ "_id": 1, "first_name": "foo1", items: [
        { "item": "sandals", "body": "feet" },
        { "item": "sandals", "body": "feet" },
        { "item": "shirts" , "body": "torso" }
    ]
},
{ "_id": 2, "first_name": "foo2", items: [
        { "item": "skirts", "where": "legs" },
        { "item": "jeans", "body": "legs" },
        { "item": "socks" , "body": "feet" },
        { "item": "sandals" , "body": "feet" }
    ]
},
{ "_id": 3, "first_name": "foo3", items: [
        { "item": "jacket", "where": "torso" },
        { "item": "socks", "body": "feet" },
        { "item": "shirts" , "body": "torso" }
    ]
}

到目前为止,我已经尝试使用 "$unwind" 和 $project 和 "$switch" 以及其他方法,但它们都不起作用。

标签: arraysmongodbaggregation-frameworkspring-data-mongodbaggregation

解决方案


推荐阅读