Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to export a mongodb query to a new collection?

What I want: I have a master collection of products, I then want to filter them and put them in a separate collection.

db.masterproducts.find({category:"scuba gear"}).copyTo(db.newcollection)

Of course, I realise the 'copyTo' does not exist.

I thought I could do it with MapReduce as results are created in a new collection using the new 'out' parameter in v1.8; however this new collection is not a subset of my original collection. Or can it be if I use MapReduce correctly?

To get around it I am currently doing this: Step 1: /usr/local/mongodb/bin/mongodump --db database --collection masterproducts -q '{category:"scuba gear"}'

Step 2: /usr/local/mongodb/bin/mongorestore -d database -c newcollection --drop packages.bson

My 2 step method just seems rather inefficient!

Any help greatly appreciated.

Thanks

Bob

like image 328
Bobby Jason Avatar asked Jun 18 '11 21:06

Bobby Jason


2 Answers

You can iterate through your query result and save each item like this:

db.oldCollection.find(query).forEach(function(x){db.newCollection.save(x);})
like image 82
renadeen Avatar answered Sep 18 '22 20:09

renadeen


  1. You can create small server side javascript (like this one, just add filtering you want) and execute it using eval
  2. You can use dump/restore in the way you described above
  3. Copy collection command shoud be in mongodb soon (will be done in votes order)! See jira feature.
like image 40
Andrew Orsich Avatar answered Sep 18 '22 20:09

Andrew Orsich