1

I have the following doc scheme:

{
    "_id": 123123123,
    "linhas": [1,2,3]
}

And i want all of them to turn to the following scheme:

{
    "_id": 123123123,
    "linhas": [{
        "id":1,
        "duracao": 14
    },{
        "id":2,
        "duracao": 14
    },{
        "id":3,
        "duracao": 14
    }]
}

I other words, i want all numbers from the array to turn into ids of objects inside the same array. How can i do that with a mongo query?

1 Answer 1

2

You can use the .aggregate() method like this:

db.collection.aggregate([
    { "$unwind": "$linhas" }, 
    { "$group": { 
        "_id": "$_id", 
        "linhas": { 
            "$push": { 
                "id": "$linhas", 
                "duracao": { "$literal": 14 }
            }
        }
    }}
])

Which returns:

{ 
        "_id" : 123123123,
        "linhas" : [
                {
                        "id" : 1,
                        "duracao" : 14
                },
                {
                        "id" : 2,
                        "duracao" : 14
                },
                {
                        "id" : 3,
                        "duracao" : 14
                }
        ]
}

You need to deconstruct your "linhas" array using the $unwind operator then $group your documents by "_id" and use the $push accumulator operator to return array of subdocuments. Of course the $literal operator let you set the value for the new field "duracao".

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

Comments

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.