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.