ThatMan
ThatMan

Reputation: 178

reverse an array and store it in a new field in all mongo documents of a collection

I have one array in mongo document. I need to reverse this array and add a new array(with reversed value) in the document. I need to do this for all the document in the mongo collections. How do I do it? I am trying with below script but this is taking a lot of time so need a faster way to do it

db.collections.find().forEach(function (doc) {
    var loc = [ doc.sourceArray[1], doc.sourceArray[0] ]; 
    db.collections.update(doc, { $set: {destinationArray: loc } });
})

Upvotes: 1

Views: 197

Answers (1)

mickl
mickl

Reputation: 49945

You can use $addFields to generate new field and $reduce + $concatArrays to scan one array and create reversed one. Then you need $out to redirect your aggregation results into a new collection. If you specify the same collection name, current collection will be overwritten

db.collection.aggregate([
    {
        $addFields: {
            reversedArray: {
                $reduce: {
                    input: "$array",
                    initialValue: [],
                    in: {
                        $concatArrays: [ ["$$this"], "$$value" ]
                    }
                }
            }
        }
    },
    {
        $out: "collection"
    }
])

Mongo Playground

Upvotes: 1

Related Questions