1

I am using the below query to change the field name

router.get("/rename", function (req, res) {
    var db = req.db;
    var collection = db.get('Users');
    collection.update({ "Age" : "Male" }, { $rename: { "Age":"Sex" } })
});

The document structure is like

{
    "_id": {
        "$oid": "55bb3b93324467d01e09c5c0"
    },
    "Sex":"Male",
    "Age": "23",
    "userId": "1014366544066103",
    "emailId":"someid"
}

Here I am trying to change field name Age to Sex, if the Age field contains Male.

But for some reason it is not changing it

I don't get any errors too

Vignesh Subramanian
  • 7,161
  • 14
  • 87
  • 150
  • 1
    What does the document look like? Are you trying to change multiple documents and did not use `{ "multi" true }` – Blakes Seven Jul 31 '15 at 10:00
  • yes i am trying to change multiple documents, will add details on document structure to question now – Vignesh Subramanian Jul 31 '15 at 10:01
  • Does this answer your question? [How can I rename a field for all documents in MongoDB?](https://stackoverflow.com/questions/9254351/how-can-i-rename-a-field-for-all-documents-in-mongodb) – Liam Feb 16 '21 at 15:47

1 Answers1

5

I think you are looking at a different document than the first one affected. The only problem I see here is the lack of { "multi": true }:

collection.update(
    { "Age" : "Male" }, 
    { "$rename": { "Age":"Sex" } },
    { "muti": true }
)

That should update all documents. Without it only the "first" match is affected.

Also, check your documents. The example you added already has a "Sex" field.

To safely fix this then:

collection.update(
    { "Age" : "Male", "Sex": { "$exists": false } }, 
    { "$rename": { "Age":"Sex" } },
    { "muti": true }
)

So there is no conflict.

And you can fix ones as listed with "both" fields as "Male" with:

collection.update(
    { "$where": "return this.Age = this.Sex" }, 
    { "$unset": { "Age": 1 } },
    { "muti": true }
)

As $unset will remove the duplicated field there.

Blakes Seven
  • 49,422
  • 14
  • 129
  • 135