2

I have mongodb collection say collectionA which have document structure like this:

{
  "_id": ObjectId("xyz"), 
  "username": "XYZ", 
  "funds": [{doc}, {doc}, ...], 
  "checkout": {nested doc} 
}

I've realized that this will grow a lot. Therefore I want to split all documents in this collection into two as below:

{
  "_id": ObjectId("xyz"), 
  "username": "XYZ", 
  "funds": [...] 
}

&

{
  "_id": ObjectId("xyz"), 
  "username": "XYZ", 
  "checkout": {nested doc} 
}

With ID & username being same for corresponding entries in both collections.

I could find copying complete document from one collection to another via copyTo(), but what I am looking for is something different. How can I achieve this?

Thanks in advance.

Paresh Nagore
  • 336
  • 2
  • 7
  • 23
  • There is no "instant too" if that is what you are asking. You likely need to iterate and create the new collection. Since it's a new collection you could possibly make use of the aggregation [`$out`](https://docs.mongodb.com/manual/reference/operator/aggregation/out/) pipeline stage, but it's not really clear in your question what the "split" should actually be. I would have thought the general idea would be to remove the embedded documents in the array and write them to a new collection, with a "foreign key" property referring to the parent. – Neil Lunn Jun 12 '17 at 07:30
  • I'd like to clarify that there is no parent and child. I just want to copy three fields from original collection to new one. If copying is successful, I can delete one of copied field (funds or checkout) from original collection. After this operation they are independent collections. – Paresh Nagore Jun 12 '17 at 07:38
  • Why not copy the collection and the [`$unset`](https://docs.mongodb.com/manual/reference/operator/update/unset/) the undesired fields then? Like I said there is "no tool" to allow a "copy" with selecting fields. You roll it yourself instead. You have been given a few different approaches there. So why not go and actually try something? – Neil Lunn Jun 12 '17 at 07:41
  • Thanks. I will try these. – Paresh Nagore Jun 12 '17 at 07:54

0 Answers0