开发者

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

开发者 https://www.devze.com 2023-03-14 02:09 出处:网络
What I want: I have a master collection of products, I then want to filter them and put them in a separate collec开发者_JS百科tion.

What I want: I have a master collection of products, I then want to filter them and put them in a separate collec开发者_JS百科tion.

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


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

db.oldCollection.find(query).forEach(function(x){db.newCollection.save(x);})


  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.


You should be able to create a subset with mapreduce (using 'out'). The problem is mapreduce has a special output format so your documents are going to be transformed (there is a JIRA ticket to add support for another format, but I can not find it at the moment). It is also going to be very inefficent :/

Copying a cursor to a collection makes a lot of sense, I suggest creating a ticket for this.


there is also toArray() method which can be used:

//create new collection 
db.creatCollection("resultCollection")

// now query for type="foo" and insert the results into new collection
db.resultCollection.insert( (db.orginialCollection.find({type:'foo'}).toArray())
0

精彩评论

暂无评论...
验证码 换一张
取 消