Where to use java script var

I would like to use a java variable in the $out stage.
This fails unless i use $out : “pricing_ods”
I don’t understand why the varabile db_ods can be used on the drop() but not in the aggregation.
thanks
-Dave

var db_pim = db.getSiblingDB('pim_read_store')
var db_ods = db.getSiblingDB('pricing_ods')

db_ods.stg_c1.drop()

db_pim.item_collection.aggregate([
    { "$project": {
        "PartId": "$windecsPartId"
    }},
    { $out: { db: db_ods, coll: "stg_c1" }}
]);

Hello @David_Lange,

Instead try this:

var db_ods = ‘pricing_ods’;

In the shell you can see that from var db_ods = db.getSiblingDB(‘pricing_ods’), the variable db_ods is of type object. You can verify this:

typeof db_ods

But, for var db_ods = ‘pricing_ods’; the typeof returns a string. The { $out: {db: db_ods, coll: “stg_c1” }} is expecting string values for db and coll fields.

Hi @David_Lange,

It would be helpful to include the error message and your specific version of MongoDB server for context, but I expect the error you are getting is similar to:

uncaught exception: Error: command failed: {
	"ok" : 0,
	"errmsg" : "wrong type for field (db) object != string",
	"code" : 13111,
	"codeName" : "Location13111"
}

JavaScript objects may have different representation depending on the usage context. For example, in the mongo shell, calling print() on an object will implicitly call object.tojson() (which is a feature of the mongo shell). You can also invoke standard JavaScript methods like object.toString().

I think you want to keep your db_ods variable as a DB object so you can call collection methods, but should explicitly call toString() to get the expected representation in the context of your aggregation query:

db_pim.item_collection.aggregate([
    { "$project": {
        "PartId": "$windecsPartId"
    }},
    { $out: { db: db_ods.toString(), coll: "stg_c1" }}
]);

Note: all of the JavaScript in this example is being evaluated in the mongo shell before the aggregation query is sent to the MongoDB server. As @Prasad_Saya mentioned, you can check the result type of a statement using the typeof JavaScript operator:

> typeof(db_ods)
object
> typeof(db_ods.toString())
string

Regards,
Stennie

super helpful thanks.

1 Like

great info appreciate the help!

1 Like

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