Insert values from one collection to fields in another collection

Hi all,

I need to insert data from one collection to fields in another collection.

For exmaple, I have the collection “A”, with these kind of documents:
FILE_TYPE : “P”,
ZONE_ID : 1,
FILE_NAME : “A_PDMM_BINARY”

and I need to insert the values above into another collection “B”, where fields names are different. So, every document from collection “A” will be inserted to collection “B” with these slightly different field names:
FileType : “P”,
ZoneId : 1,
FileName : “A_PDMM_BINARY”

What would be the best way to achieve this?

Thanks,
Tamar

Done it using:
db.A.find({}}).
forEach( function(i) {
db.B.insert(i);
});

Then renames the fileds using
db.B.updateMany(
{ },
{ $rename: { “FILE_NAME”: “FileName” } }
)

1 Like

Doing a single insert for each document of A is probably very slow.

Alternatives are:

  1. Doing insertMany()
  2. Use $out stage in an aggregation.

For you whole use-case you may use $set, $unset with $out for renaming.

db.A.aggregate( [
  { "$set" : { "FileName" : "$FILE_NAME" } } ,
  { "$unset" : [ "FILE_NAME" ] } ,
  { "$out" : "B" }
] )

Thank you for reply @steevej !

Works like a charm.

Thanks,
Tamar

1 Like

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