Satwinder Singh
Satwinder Singh

Reputation: 627

How to write Shell Script for Mongo Find query.?

I am new to shell scripting. Actually I am writing a shell script for mongo to find specific document, this shell script accepts an argument and uses in find. I had written a simple find query:

mongo poc --eval "printjson(db.users.find().toArray())"

That's working fine, but now problem is that when I want to find specific document by passing users id that gives null records, so here is my shell script:

mongo poc --eval "printjson(db.users.find({"userid":"$1"}).toArray())"

I don't know what is wrong, please help so that i would be able to write for update and remove query as well.

Upvotes: 1

Views: 2290

Answers (1)

Stennie
Stennie

Reputation: 65303

The issue is that you are trying to use double quotes inside a quoted string in your Bash script.

You should either:

  • Use single quotes:

    #!/bin/bash
    
    mongo poc --eval "printjson(db.users.find({'userid':'$1'}).toArray())"
    
  • Escape the double quotes inside the string:

    #!/bin/bash
    
    mongo poc --eval "printjson(db.users.find({\"userid\":\"$1\"}).toArray())"
    

For more details, see: Bash quotes and escaping.

Upvotes: 4

Related Questions