Well, you are already setting the database in use as you connect via:
mongo localhost:27017/dbname
So it is now on database "dbname". That is carried through to the db variable. Which is just a placeholder for the "current" database object.
That means that anything in your "script":
var results = db.collection.find().toArray();
For example is using the database you selected and the collection you named.
Need more? This is valid to:
db["mycollection"].find();
It's just JavaScript to the shell.
if you want a collection to be set as a variable then do something like this:
mongo localhost/mydb --eval "var users = db.users" myfile.js
Or otherwise just do that in you JavaScript file. You can test that by:
mongo localhost/mydb --eval "var users = db.users" --shell
And in the shell you now have a variable users that is "aliased" to the users collection.