0

I have a script like below and I am running queries in mongodb. But when I call it as a function, it adds single quote and my query doesn't work. How can i solve this problem?

My Code:

mongo_func() {
        mongo "$MONGO/$1" --quiet --eval $2 $3 $4
}

mongo_func "Users" 'db.ucol.updateMany({}, { $unset : {"name" : "", "Users": ""}});'

When I debug with bash -x, the output looks like below.

mongo 10.10.1.2/Users --quiet --eval 'db.ucol.updateMany({},' '{$unset:' '{"name"' : '"",' '"Users":' '""}});'

It s working as follows properly.

mongo 10.10.1.2/Users --quiet --eval 'db.ucol.updateMany({}, {$unset: {"name" : "", "Users": ""}});'
MrTux01
  • 343
  • 3
  • 9
  • 1
    Probably you can replace the function by `FIRST="$1"; shift; mongo "$MONGO/$FIRST" --quiet --eval "$@";` – ecm Mar 22 '22 at 11:38

1 Answers1

2

That's because you have failed to quote the function arguments.

Try this instead.

mongo_func() {
    user=$1
    shift
    mongo "$MONGO/$user" --quiet --eval "$@"
}
tripleee
  • 175,061
  • 34
  • 275
  • 318