Arijit
Arijit

Reputation: 1674

Update MongoDB collection toLowercase for array field

I have already seen these two posts

Update MongoDB collection using $toLower

and

To loop through non associative array in mongoDB

But those didn't helped me.

I have a collection with few documents like this:

{
"_id": "58bda97de000ae205f77c6e0",

"artistName": "ABC",

"trackNames": [
"1A",
"1B",
"1C",
"1D"
],
}

I want to change all the values of trackNames field to lowercase.Like this:

{
    "_id": "58bda97de000ae205f77c6e0",

    "artistName": "ABC",

    "trackNames": [
    "1a",
    "1b",
    "1c",
    "1d"
    ],
    }

Till now I tried like this:

db.artist.find().forEach(function(e) {
e.trackNames.forEach(function(i){
i=i.toLowerCase();
db.artist.save(e)})})

But its not working. Please help.

Upvotes: 0

Views: 1062

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191779

i = i.toLowerCase() does not actually update the object. Instead you can replace the array itself with a map:

e.trackNames = e.trackNames.map(function (trackName) {
  return trackName.toLowerCase();
});

This will update the trackNames array on the original object which you can then save.

Upvotes: 1

Related Questions