2

I'm trying to convert the "interesse" array into a new object with 2 fields "term" which is the current array terms and a statistic value with the name "str" with a starting value of 0
as the following example. my database currently has about 16KK entries so i'm trying to create some sort of function or routine to deal with it.

Original documents

{
    "email" : "[email protected]",
    "interesse" : [ 
        "Calcados", 
        "Acessorios para viagem", 
        "Interesse em noticias sobre curiosidades"
    ],
    "data" : "2017-01-30"
}

{
    "email" : "[email protected]",
    "interesse" : [ 
        "Eletrodomesticos e portateis", 
        "Geladeiras"
    ],
    "data" : "2017-01-30"
}

Result documents

{
    "email" : "[email protected]",
    "interesse" : [ 
        {"term":"Calcados","str":0}, 
        {"term":"Acessorios para viagem","str":0},
        {"term":"Interesse em noticias sobre curiosidades","str":0}
    ],
    "data" : "2017-01-30"
}

{
    "email" : "[email protected]",
    "interesse" : [ 
        {"term":"Eletrodomesticos e portateis","str":0}, 
        {"term":"Geladeiras","str":0},
    ],
    "data" : "2017-01-30"
}

I was looking at arrayToObject.. but the function only transforms the entire array into a single object... what i want is to transform each value into new object...

1 Answer 1

2

You need $addFields to replace existing field and $map to transform your current array:

db.collection.aggregate([
    {
        $addFields: {
            interesse: {
                $map: {
                    input: "$interesse",
                    in: {
                        term: "$$this", str: 0
                    }
                }
            }
        }
    }
])

Mongo Playground

Sign up to request clarification or add additional context in comments.

2 Comments

Great! thanks! didnt know how to use map. can you xplain the meaning of $$this for me?
@filscapo when using $map you can use as to explicity name the variable which represents currently processed element but you can also skip it as it default to this (docs.mongodb.com/manual/reference/operator/aggregation/map/…)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.