简体   繁体   中英

How to move an array value from one collection to another collection?

I have an array value in one collection. I want to move the array value from one collection to another collection.

fruits : [ 
           { "apple","banana" } 
         ]

how to move this array value value from one collection to another collection?

I am thinking to do like, get values from one collection, store it in a temp variable and then update another collection to add this temp variable. But I know this is not the simple way.

So, I wonder is there any simple way to do this?

Hope I am clear with my question. Any help would be appreciated.

I am thinking to do like, get values from one collection, store it in a temp variable and then update another collection to add this temp variable. But I know this is not the simple way.

As @sergio pointed out. That is most likely the simplest way.

MongoDB has no cross collection update that would allow you to do this all within a single update call (unlike in SQL whereby you do).

Of course that being said it is not impossible for MongoDB to do it, rather that it is simply not implemented as of yet.

Of course, it is advised to not do this sort of thing regularly otherwise you could get massive problems with performance especially if those documents need moving out of their current record allocation to a new one (due to difference in size).

Considering what you wish to push upto another collection is a subdocument I also would not advise using the aggregation framework to create a "display" of your data that can easily be saved to the alternative collection. This is since the data is already preformed and using the aggregation framework would just complicate things.

Instead I would just iterate the source documents, get the values out and simply push them to the documents in the destination collection.

If these documents are new and you are looking to do a type of aggregation you could also use Map Reduce. I should warn you that MR is not really designed to move values across documents but more to formulate aggregated documents and save them to a collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM