I am running from mongosh. Can I use the “db” and “col” variable in the into: { db:“db”, coll:“col”} of the merge? Or does a better approach exist?
thanks in advance.
var db = db.getSiblingDB('db_test');
var col = db.product;
function convert() {
col.aggregate(
[ { $match :{"Quantity": { $type: 1 }}},
{ $addFields:{"Quantity": { $convert:
{input: "$Quantity", to: "int" }}}},
{ $merge :{ into: { db:"db", coll:"col"}, on: "PartId", whenMatched: "replace"} }
], {allowDiskUse: true} )
};
Hello @David_Lange, you can use the variables representing the names of the collection and the database being used in the $merge aggregation stage’s intofield. Note the database and collection names need to be strings. That is using like this is fine:
Alternatively to Prasad_Saya method you could use the getName() methods available in both your db and col variables.
var db = db.getSiblingDB('db_test');
var col = db.product;
// ...
{ $merge : { into : { db: db.getName() , coll : col.getName() },
on: "PartId",
whenMatched: "replace" } }