Mithil Mohan
Mithil Mohan

Reputation: 243

Replace all occurences of a substring in a field in all documents in MongoDB

I have a collection Brands, I have to replace the path ./assets/ to D:/data/db/images , I have multiple occurrences of this in multiple documents. How do I acheive this using a query ?

Sample of each document

{"name":"Dell","images":["./assets/dell1.jpg","./assets/dell2.jpeg","./assets/dell3.jpg"],
             "captions":["Yours is here","Easy as dell","Uniquely you"],
             "logo":"./assets/dell4.png",
             "details":{"headOffice":"Bangalore","address":"No.12/1, Divyashree Green, Koramangala Inner Ring Rd, Domlur, Bengaluru - 560071",
             "phoneNumber":"(080) 28077000  ","website":"www.dell.com"}
             }

Upvotes: 1

Views: 2600

Answers (1)

mickl
mickl

Reputation: 49945

You can use Aggregation Framework's $out operator to redirect the output of your aggregation to particular collection. If you specify the same collection name then it will replace existing collection.

To overwrite existing field you can use $addFields operator. Then you just have to remove the length of ./assets/ using $substr and concatenate that with your new prefix using $concat

db.Brands.aggregate([
    {
        $addFields: {
            images: {
                $map: {
                    input: "$images",
                    as: "image",
                    in: {
                        $concat: [ "D:/data/db/images", { $substr: [ "$$image", 8, { $strLenBytes: "$$image" } ] } ]
                    }
                }
            }
        }
    },
    { $out: "Brands" } //replaces existing collection
])

In MongoDB 3.2 you can run following script:

db.Brands.find().forEach(function(doc){
    doc.images = doc.images.map(function(image){ return image.replace("./assets/","D:/data/db/images/") })
    db.Brands.save(doc);    
})

Upvotes: 2

Related Questions