I am missing something very fundamental to working within the shell.
The shell and server are 4.4.3. I don’t understand why I can declare a VAR for a DB and COLLECTION as one object and use it in a MQL. For example
MongoDB Enterprise PRIMARY> var col=db.product;
MongoDB Enterprise PRIMARY> col.find({}).count()
14027623
But I can’t define each component independently.
MongoDB Enterprise PRIMARY> var d=db
MongoDB Enterprise PRIMARY> var c=product
uncaught exception: ReferenceError: product is not defined :
Thanks
-Dave
David_Lange:
var c=product
uncaught exception: ReferenceError: product is not defined :
Hi @David_Lange ,
Per the error message, the problem is that product
in this assignment context is expected to be a variable. You can use the typeof()
method to check the type of a value:
> typeof(product)
undefined
> typeof('product')
string
If product
happens to be a variable with a defined value, it can be used as the value for an assignment:
> var product = 'widgets'
> c=product
widgets
To assign the literal string product
as a value, you need to use quotes:
var c = ‘product’
To fetch a collection using a variable, use db.getCollection()
.
> var c = 'product'
> db.getCollection(c).find()
For some general tips (and differences between scripted & interactive mongo
), see: Write Scripts for the mongo
Shell .
Regards,
Stennie
2 Likes
system
(system)
Closed
March 23, 2021, 4:23am
3
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.