Categories
Uncategorized

Copying (duplicating) MongoDB Documents (Rows)

The use case is simple – I have one row (I mean document). I need to make multiple copies of it. Say, I am building a blog app and I need to quickly generate a few posts on the database. Scripting is one way to do it, but if I need to do this only once, automation is a waste of time.

Thanks to mongodb’s shell and JS-like APIs. This is actually simple.

Connect to mongodb:

Select the database:

Find an entry on the “posts” collection:

Now let’s change the “_id”:

X is now a whole new object/document (since we changed the “_id”). We can alter other fields as well. Let’s store it:

You just copied one document into a new document. Cool?

The command line mongo client has readline and history support. So you can actually use the up arrow to repeat the commands quite easily.

7 replies on “Copying (duplicating) MongoDB Documents (Rows)”

Thanks!

I tried with delete x._id but it gives problems (integer numbers are converted to double). Your solution works perfectly.

Your solution not work when the post object have other objects inside it.

received mongodb dup key error.

Masnun,

 

Thanks a million mate, straight to the point. When you google a solution to this problem everyone takes you on a world tour to no where when you slab it in 3 commands.

Many thanks

Simon Adams

Comments are closed.