How can I insert specific documents from one collection to another

Hi all,

Is there a way to copy certain documents (eg. with “Color”: “Blue” or “Red”) from one collection to another in MongoDB using .bat and .js?

My initial idea to complete this was to run a .find query to loop through the first collection to find the relevant documents using .forEach(function( ) then pass an insert statement to put the documents into the second collection but I haven’t been able to make this work as of yet.

Full disclosure, I’m very new to MongoDB so forgive me if this is easily done or not possible.

Thanks for any help :slight_smile:

Take a look at

and

1 Like

Thanks, this is almost perfect! I have been able to export and import some files, but it seems as though Mongo has created duplicate ID’s so I am unable to import most of the documents from the first collection into the second. I have tried to exclude importing and exporting the _id Objects however, it doesn’t seem to work when using JSON and JavaScript. Do you know any way I can exclude importing the _id Objects so that when they are imported they are given new ones?

You could use jq Manual (development version) to modify the documents between the export and import.

My work laptop won’t allow me to install jq. I’ve managed to work out a way of inserting the documents into another collection by using the long hand below:

db.Workbook.find({ $or: [{type:"Slip/Binder - New Business"}, {type:"Slip/Binder - Renewal"}] }).forEach(function(workbook){
		printjson(workbook._id);
		if (workbook.businessEntity.associationId !=null){
			printjson("Found submisison ID")
			var submission=db.WorkbookView.findOne({"businessEntity.associationId":workbook.businessEntity.associationId});
			if (submission==null){ {$count:
				printjson("Inserting document")
				var newView={};
				newView._id=new ObjectId();
				newView.businessEntity=workbook.businessEntity;
				newView.createdDate=workbook.createdDate;
				newView.workbookStatus=workbook.workbookStatus;
				newView._class="net.travp.workbookviewlistener.dto.WorkbookView";
				printjson(newView);
				db.WorkbookView.insert(newView);
			}}
				else{ print("Workbook Submission already exists!")}	
		}
});

now I’ve just got to figure ou how to add a count to the script

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.