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:
1 |
mongo |
Select the database:
1 |
use blog |
Find an entry on the “posts” collection:
1 |
x = db.posts.findOne() |
Now let’s change the “_id”:
1 |
x._id = new ObjectId() |
X is now a whole new object/document (since we changed the “_id”). We can alter other fields as well. Let’s store it:
1 |
db.posts.insert(x) |
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.
how to Move data from one document to another document in mongodb?
can we get same document with same objectId by aggerigation
May be. Depends on what you intend to do.
Your solution not work when the post object have other objects inside it.
received mongodb dup key error.
Yes, the idea is the same though. Overwrite what you need to.
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