skip to Main Content

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

3

Answers


  1. Chosen as BEST ANSWER

    Found a workaround:

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

    But I guess there's a better way to do it without a pipe.


  2. You could also use the mongosh:

    db.people.find(
        { status: "A" }
    ).forEach({doc => 
       print(doc.Url)
    })
    

    If it does not work, try db.people.find(...).toArray().forEach(...).

    As a one-liner

    mongosh "mongodb://localhost:27017/db" --quiet --eval "db.collection.find({ 'Id': '5400490185'}).forEach(doc => {print(doc.Url)})"
    https://example.org
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search