Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Subset of MongoDB Collection to Another Collection

Tags:

mongodb

I have a set like so

{date: 20120101} {date: 20120103} {date: 20120104} {date: 20120005} {date: 20120105} 

How do I save a subset of those documents with the date '20120105' to another collection?

i.e db.subset.save(db.full_set.find({date: "20120105"}));

like image 518
SemperFly Avatar asked Mar 14 '12 22:03

SemperFly


People also ask

How do I copy a collection to another collection in MongoDB?

MongoDB – copyTo() Method In MongoDB, copyTo() method is used to copies all the documents from one collection(Source collection) to another collection(Target collection) using server-side JavaScript and if that other collection(Target collection) is not present then MongoDB creates a new collection with that name.

How do I link two MongoDB collections?

For performing MongoDB Join two collections, you must use the $lookup operator. It is defined as a stage that executes a left outer join with another collection and aids in filtering data from joined documents.

How do I save a collection in MongoDB?

MongoDB's update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method.

How do I capture a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});


2 Answers

I would advise using the aggregation framework:

db.full_set.aggregate([ { $match: { date: "20120105" } }, { $out: "subset" } ]) 

It works about 100 times faster than forEach at least in my case. This is because the entire aggregation pipeline runs in the mongod process, whereas a solution based on find() and insert() has to send all of the documents from the server to the client and then back. This has a performance penalty, even if the server and client are on the same machine.

like image 157
melan Avatar answered Sep 20 '22 11:09

melan


Here's the shell version:

db.full_set.find({date:"20120105"}).forEach(function(doc){    db.subset.insert(doc); }); 

Note: As of MongoDB 2.6, the aggregation framework makes it possible to do this faster; see melan's answer for details.

like image 35
Eve Freeman Avatar answered Sep 20 '22 11:09

Eve Freeman