Search code examples
mongodbbashshellmongo-shell

mongodb in bash/shell: try to fetch specific values from CLI


I try to use 'mongoexport' to retrieve the 'Url' value:

$ mongoexport -d "db" -c "collection" -q '{"Id":"5400490185"} | jq .

return:

{
  "_id": {
    "$oid": "641e8845c0a3fde195b5901b"
  },
  "Url": "https://example.org",
  "Id": "5400490185",
  "Title": "xxx",
  "Description": "foobar",
  "Date_Time": "1679697365"
}

Now I try to fetch only 'Url', from the doc https://www.mongodb.com/docs/manual/reference/sql-comparison/ should be

db.people.find(
    { status: "A" },
    { user_id: 1, status: 1, _id: 0 }
)

so I try:

$ mongoexport -d "db" -c "collection" -q '{"Id":"5400490185"}, {"Url": "1", _id: "0"}'

but I get

invalid character ',' after top-level value

What's wrong?

Tried also:

$ mongoexport -d "db" -c "collection" -q '{"Id":"5400490185"}' -f 'Url'

But doesn't produce what's expected


Solution

  • It's far easier in Python and shell here-doc ('mongodb' JS query syntax is awful IMHO):

    #!/bin/bash
    
    mydb='foobar'
    
    if [[ ! $1 ]]; then
        cat<<-EOF >&2
        Usage: ${0##*/} <collection> [id]
        EOF
        exit 1
    fi
    
    if [[ $2 ]]; then
        python<<-EOF
        from pymongo import MongoClient
        client = MongoClient('mongodb://localhost:27017/')
        mydb = client['$mydb']
        mycol = mydb["${1:?}"]
        c = mycol.find_one({"Id": "$2"})
        print(c['Title'], c['Description'], c['Url'], sep="\\n")
        client.close()
        EOF
    else
        python<<-EOF
        from pymongo import MongoClient
        client = MongoClient('mongodb://localhost:27017/')
        mydb = client['texas']
        mycol = mydb["${1:?}"]
        for c in mycol.find():
            print(c['Url'], c['Title'], c['Description'], sep="\\n")
        client.close()
        EOF
    fi
    

    Usage:

    Usage mongo-parse.sh <collection> [id]
    

    Simple, clear, efficient.