Alexander Mills
Alexander Mills

Reputation: 100190

Use shell variables in MongoDB query

Is there a way to use shell variables in a MongoDB query?

I have this for example:

#!/usr/bin/env bash

mongo --eval "use cdt_db; db.users.update({username:'${USER}'}, {'\$set':{roles:['Admin']}});"

I tried single quotes and double quotes, I get this error:

MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
2017-10-09T13:53:51.747-0700 E QUERY    [thread1] SyntaxError: missing ; before statement @(shell eval):1:4

Upvotes: 3

Views: 5361

Answers (1)

randomir
randomir

Reputation: 18697

From the shell standpoint, your query is fine. Variable USER is expanded properly and $ in $set is properly escaped to prevent the shell parameter expansion.

The problem is in your use <dbname> part of the query. According to the docs:

You cannot use any shell helper (e.g. use <dbname>, show dbs, etc.) inside the JavaScript file because they are not valid JavaScript.

Instead, you can use a JavaScript equivalent:

db = db.getSiblingDB('<dbname>')

or, better yet, specify the name of the database via command line argument:

mongo dbname --eval 'query'

Fixed, your query looks like:

mongo cdt_db --eval "db.users.update({username:'${USER}'}, {\$set:{roles:['Admin']}});"

For convenience (less escaping), you might sometimes also consider using single quotes, and concatenate the expanded variables (under double quotes):

mongo cdt_db --eval 'db.users.update({username:"'"${USER}"'"}, {$set:{roles:["Admin"]}});'

Upvotes: 3

Related Questions