Mongosh variable in a pipeline

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() {
    [  { $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 into field. Note the database and collection names need to be strings. That is using like this is fine:

{ $merge:{ into: { db: "db_test", coll: "product" }, ... }

The collection name is “product” and database name is “db_test”.

To use variables for database and collection names, try this:

// Define variables
var db_name = "db_test"
var coll_name = "product"

// Use in your aggregate method
{ $merge:{ into: { db: db_name, coll: coll_name }, ... }

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" } }
1 Like

I can see the db.getName() method in the documentation; I couldn’t locate the db.collection.getName() method (though it works fine).

That’s weird.

I found out about it by using TAB for text completion after typing:

db.getCollection( "abc" ).TAB

this works good. thanks!