INSERT INTO collection db.find() ?

Ever needed that handy INSERT INTO xxx SELECT FROM xxx when sailing the high seas with a Mongo DB?

Well – heres an easy workaround, I call it…

insert into collection from collection:

db.searchCollectionName.find().forEach(function(doc){
db.insertCollectionName.insert(doc); // insert each doc found
});

As you can see – you are using the find method so you are free to specify a projection or use filtering criteria as you like.. e.g.

db.searchCollectionName.find( { “a” : 1 } ).forEach(function(doc){
db.insertCollectionName.insert(doc); // insert each doc found
});

The equivalent SQL of two statements in one:
CREATE TABLE / INSERT INTO insertCollectionName
SELECT * FROM searchCollectionName WHERE a = 1;

Have fun!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s