How to replace a value of an array in MongoDB aggregation?

Viewed 132

I'm trying to replace the value only in the aggregation result, not in the stored document, thats why I use an aggregation and not a update.

Suppose these are the documents stored in the collection:

{ "_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" }
    ]
}

The aggregation must replace "gloves" by "sandals", and it correspondent attribute "body" from "hands" to "feet". The expected result is:

{ "_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" }
    ]
}

So far, I've tried using "$unwind" and $project with "$switch", among other approaches, but none of them work.

0 Answers
Related