Search code examples
javascriptmongodbrenamebsondatabase

How to rename a Stored JavaScript in MongoDB?


Consider, I have a following Stored JavaScript in MongoDB

{_id: "sum",
 value: function (x, y) { return x + y; }}

It is been created by following command in MongoDB shell

db.system.js.save({_id: "sum",
value: function (x, y) { return x + y; }});

It can be run like:

db.eval("return sum(3, 5);");
8.0

Question: I want to change the name of my Stored JavaScript sum to GetAddResult. How can I do this without creating new Stored JavaScript?


Update:
I tried the following command to rename it.

db.system.js.update({'_id':'sum'}, {'$set':{'_id':'GetAddResult'}});
Mod on _id not allowed

Solution

  • You cannot update the _id field of a mongodb document. Its an immutable object and hence you cannot alter the Object Id after creation of a document.

    But you can try adding a new document with the preffered _id you would like to have.