Shaleesh Madhavan
Shaleesh Madhavan

Reputation: 47

How to update array of objects to LowerCase in mongodb?

I need to update the role in team array to lowercase.

db.users.find().pretty().limit(1)
    {
            "_id" : ObjectId("5d9fd81d3d598088d2ea5dc9"),
            "employed" : "USA-Atlanta",
            "firstName" : "Rory",
            "siteRole" : "super admin",
            "status" : "active",
            "team" : [
                    {
                            "name" : "SALES AND MARKETING",
                            "displayName" : "S&M",
                            "role" : "Manager"
                    }
            ]
    }

Tried this code.I m getting it with normal fields.

db.users.find( {}, { 'role': 1 } ).forEach(function(doc) {
db.users.update(
   { _id: doc._id},
   { $set : { 'role' : doc.role.toLowerCase() } },
   { multi: true }
)
});

sample output

"team" : [
                {
                        "name" : "SALES AND MARKETING",
                        "displayName" : "S&M",
                        "role" : "manager"
                }
        ]

Upvotes: 0

Views: 1383

Answers (1)

hhharsha36
hhharsha36

Reputation: 3349

I think the below Aggregation query is what you are looking for

var count = 0;
db.users.aggregate([
    {
        "$match": {
            "team.role": {$exists: true}
        }
    },
    {
        "$project": {
            "_id": 1,
            // "team": 1,
            "teamModified": {
                "$map": {
                    "input": "$team",
                    "as": "arrayElems",
                    "in": {
                        "$mergeObjects": [
                            "$$arrayElems",
                            {"role": {"$toLower": "$$arrayElems.role"}}
                        ]
                    }
                }
            }
        }
    },
]).forEach(function(it) {
    db.users.updateOne({
        "_id": it["_id"]
    }, {
        "$set": {
            "team": it["teamModified"]
        }
    })
    printjson(++count);
})
printjson("DONE!!!")

Note: I haven't tested the script properly in my local, so do let me know if it didn't help you out

Upvotes: 3

Related Questions