Smarticles101
Smarticles101

Reputation: 1926

MongoDB Replace _id field with existing field Id

I have an existing mongo collection. Each object inside looks similar to this:

{
  "_id": ObjectId("..."),
  "Id": 4321,
  ...
}

The "Id" field I have is unique to each object.

Is it possible to run a db.collection.update query in such a way as I can replace the "_id" field with the contents of "Id"?

i.e.

{
  "_id": 4321,
  ...
}

Upvotes: 0

Views: 2412

Answers (1)

Himanshu Sharma
Himanshu Sharma

Reputation: 3010

For mongo version 4.0.10, the following query can get us the expected output:

db.collection.aggregate([
    {
        $addFields:{
            "_id":"$Id"
        }
    },
    {
        $project:{
            "Id":0
        }
    },
    {
        $out:"collection"
    }
])

Data set:

{ "_id" : ObjectId("5d557c5f7c780d119a01a6de"), "Id" : 4321 }
{ "_id" : ObjectId("5d557c5f7c780d119a01a6df"), "Id" : 3412 }
{ "_id" : ObjectId("5d557c5f7c780d119a01a6e0"), "Id" : 1234 }

Output:

{ "_id" : 4321 }
{ "_id" : 3412 }
{ "_id" : 1234 }

We are performing the aggregation on 'collection' and replacing the old data with the output of aggregation.

Upvotes: 2

Related Questions