Overwrite _id field when exporting collection

I wanna overwrite _id field or create new field when exporting collection using mongoexport in mongodb version 3.6.
My output right now is

[{"_id":{"$oid":"60c8d456f3014a7a0e09eb93"},"name":"test","email":"test@mail.com","password":"$2y$10$pwGgshwbB.zuVekli5n71e9o13F7iOxKCh7t5Egwd.EgYLUA3tiSW","updated_at":{"$date":"2021-06-22T11:27:21.215Z"},"created_at":{"$date":"2021-06-15T16:24:54.852Z"},"remember_token":"06blctlK6izAuVtVV0VyKXHJH2KtoXmAHGQMiLivkMNnqzq852tuhYCFrvR9" }]

What I want is


I’m exporting using
mongoexport --uri="mongodb://test:11111111@" --collection users --jsonArray --out ~/Downloads/users.json

Can someone help me? Thanks in advance.

Hello @Patrick_Edward, the exported JSON has the _id field with ObjectId formatted as Extended JSON.

JSON can only represent a subset of the types supported by BSON. To preserve type information, MongoDB adds the extensions to the JSON format - that is the reason the _id value looks like that. When the same JSON is imported into MongoDB (using mongoimport) the _id is once again converted back as ObjectId.

And, I don’t think there is a feature to replace the _id value during the export process. But, you can restrict which fields can be exported.

Dear @Prasad_Saya
Hi. Thanks for quick reply. So if I can’t overwrite the field, maybe can I add custom field for id?


You can do almost everything you want with your JSON files with jq Manual (development version).

1 Like

Hello @Patrick_Edward, you can try this:

First, create a view on the source collection. The view definition takes an aggregation pipeline. You can create a new field as you are expecting, id (this has value of ObjectId converted to string) in the pipeline. For example,:

In mongo shell, create the view:

var pipeline = [ { $addFields: { id: { "$toString": "$_id" } } } ]
db.createView("view_for_export", "users", pipeline)

Then, in the command-line do the export using the view, instead of the collection. After the export is complete, the view can be dropped, just like you drop a collection.

mongoexport --db=test --collection=view_for_export --out=output.json

In the JSON file,

"_id" : ObjectId("5fbf724afaabe21f9bfc3eb5")
is converted to a new field:


@Prasad_Saya This is a nice answer. Thanks for it. I will try this.

@steevej Thanks. I will add this in my learning road map.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.