Insert new field called id in one mongo query

hi

how in one mongo query i can do the next > itrate on the document and insert a new field called id with a unique mongo objectID

Before:

[
 {
 	"cityId":  NumberInt(1),
 	"stateId": NumberInt(2)
 },
  {
 	"cityId":  NumberInt(9),
 	"stateId": NumberInt(8)
 }
]

After:

[
 {
 	"cityId":  NumberInt(1),
 	"stateId": NumberInt(2),
        "id": ObjectId("631ee4b7e996a64a4a791a85")
 },
  {
 	"cityId":  NumberInt(9),
 	"stateId": NumberInt(8),
        "id": ObjectId("60473638ccdab2446cd656e3")
 }
]

Hi,

You can leverage the fact that Mongo will automatically create unique ObjectId for the property _id when the document is created. So, you can just add new property called id that will have the same value as existing _id property. You can do it like this:

db.collection.update({},
[
  {
    "$set": {
      "id": "$_id"
    }
  }
],
{
  "multi": true
})

Working example

1 Like