mongodb

mongosh

[!NOTE|label:references:]

install

[!NOTE|label:references:]

  • universal

    $ version='mongosh-2.2.15-linux-arm64'
    $ curl -fsSL https://downloads.mongodb.com/compass/${version}.tgz | tar xzf - -C /opt/mongosh
    
    # setup PATH
    $ echo "export PATH=\$PATH:/opt/mongosh/${version}/bin" >> ~/.bashrc
    $ source ~/.bashrc
    
    # or link binary into PATH
    $ sudo cp /opt/mongosh/${version}/bin/mongosh_crypt_v1.dylib /usr/local/lib/
    $ sudo ln -s /opt/mongosh/${version}/bin/mongosh /usr/local/bin/mongosh
  • debain

    $ sudo apt-get install gnupg
    $ wget -qO- https://www.mongodb.org/static/pgp/server-7.0.asc | sudo tee /etc/apt/trusted.gpg.d/server-7.0.asc
    
    # ubuntu 18.04
    $ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
    # ubuntu 20.04
    $ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
    # ubuntu 22.04
    $ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
    
    # install
    $ sudo apt-get update
    $ sudo apt-get install -y mongodb-mongosh
    
    # or openssl 1.1
    $ sudo apt-get install -y mongodb-mongosh-shared-openssl11
    # or openssl 3.0
    $ sudo apt-get install -y mongodb-mongosh-shared-openssl3
  • centos

    $ sudo bash -c "cat > /etc/yum.repos.d/mongodb-org-7.0.repo" <<EOF
    [mongodb-org-7.0]
    name=MongoDB Repository
    baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/7.0/$basearch/
    gpgcheck=1
    enabled=1
    gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc
    EOF
    
    # install
    $ sudo yum install -y mongodb-mongosh
    # or openssl 1.1
    $ sudo yum install -y mongodb-mongosh-shared-openssl11
    # or openssl 3.0
    $ sudo yum install -y mongodb-mongosh-shared-openssl3
    
    # or RHEL8
    $ sudo yum install -y https://repo.mongodb.org/yum/redhat/8/mongodb-org/7.0/x86_64/RPMS/mongodb-mongosh-7.0.0-1.el8.x86_64.rpm
  • check info

    $ mongosh --build-info

configure

[!NOTE|label:references:]

# ubuntu 22.04
$ cat /etc/mongosh.conf
mongosh:
  displayBatchSize: 3000

[!NOTE|label:references:]

db_name> DBQuery.shellBatchSize = 300

# verify
db_name> config.get('displayBatchSize')
300
db_name> config.set("displayBatchSize", 3000)
Setting "displayBatchSize" has been changed
db_name> config.get('displayBatchSize')
3000
db_name> config.get('inspectDepth')
6
$ cat ~/.mongodb/mongosh/config | jq -r .displayBatchSize
3000

# or via cmd
$ mongosh --eval 'DBQuery.shellBatchSize = 2000; db...'

auto-completion

$ npm i -g @mongosh/autocomplete

local files

[!NOTE|label:references:]

  • logs

    OPERATING SYSTEMPATH

    macOS

    ~/.mongodb/mongosh/<LogID>_log

    Linux

    ~/.mongodb/mongosh/<LogID>_log

    Windows

    %LOCALAPPDATA%/mongodb/mongosh/<LogID>_log

    > Get-Content %LOCALAPPDATA%/mongodb/mongosh/<LogID>_log
  • command-line history

    OPERATING SYSTEMPATH

    macOS

    ~/.mongodb/mongosh/mongosh_repl_history

    Linux

    ~/.mongodb/mongosh/mongosh_repl_history

    Windows

    %UserProfile%/.mongodb/mongosh/mongosh_repl_history

--eval

execute command

  • list all _id

    $ mongosh "mongodb://mongodb.domain.com:27017" \
              --username username \
              --password $(pass show path/to/credential) \
              --authenticationDatabase db_name \
              --eval 'use db_name' \
              --eval 'db.collection.distinct("_id")' |
    
    # or
    $ mongosh "mongodb://mongodb.domain.com:27017" \
              --username username \
              --password $(pass show path/to/credential) \
              --authenticationDatabase db_name \
              --eval "db = db.getSiblingDB('db_name'); db.collection.distinct('_id')" |
      tr "'" '"'
    

eval command and show as json format

$ mongosh "mongodb://mongodb.domain.com:27017" \
          --username username \
          --password $(pass show path/to/credential) \
          --authenticationDatabase db_name \
          --json=relaxed \
          --eval 'use db_name' \
          --eval 'printjson(db.collection.distinct("_id"))'

# or
$ mongosh "mongodb://mongodb.domain.com:27017" \
          --username username \
          --password $(pass show path/to/credential) \
          --authenticationDatabase db_name \
          --eval "db = db.getSiblingDB('db_name'); printjson(db.collection.distinct('_id'))" |
  tr "'" '"'

interactive mode

[!NOTE|label:references:]

connect to remote server

[!NOTE|label:references:]

# login
$ mongosh --host mongodb.domain.com \
          --port 27017 \
          --username 'username' \
          --password $(pass show path/to/credential) \
          --authenticationDatabase 'db_name'

# or
$ mongosh 'mongodb://mongodb.domain.com:27017' \
          --username 'username' \
          --password $(pass show path/to/credential) \
          --authenticationDatabase 'db_name'

Current Mongosh Log ID: 66b5a880d70a325006838725
Connecting to:          mongodb://<credentials>@mongodb.domain.com:27017/?directConnection=true&authSource=db_name&appName=mongosh+2.2.15
Using MongoDB:          6.0.2
Using Mongosh:          2.2.15
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
test>

# use database
test> use db_name
switched to db db_name

db_name> db.hello()
{
  isWritablePrimary: true,
  topologyVersion: {
    processId: ObjectId('6616e407a0520bbbc6dbeace'),
    counter: Long('0')
  },
  maxBsonObjectSize: 16777216,
  maxMessageSizeBytes: 48000000,
  maxWriteBatchSize: 100000,
  localTime: ISODate('2024-08-09T05:52:20.150Z'),
  logicalSessionTimeoutMinutes: 30,
  connectionId: 235951,
  minWireVersion: 0,
  maxWireVersion: 17,
  readOnly: false,
  ok: 1
}

utility

[!NOTE|label:references:]

db_name> help
db_name> db.collection.help()

# show dbs
test> show dbs

# get current db name
db_name> db.collection.getDB()
db_name

# get current collection name
db_name> db.collection.getName()
collection

# get stat of collection
db_name> db.collection.stats()

show all tables

[!NOTE|label:references:]

db_name> db.getCollectionNames()

# or
db_name> show tables

# or
db_name> show collections
  • fileter tables

    db_name> db.getCollectionNames().filter( function(CollectionName) { return /klocwork/.test(CollectionName) })
    [ 'klocwork', 'klocwork_new' ]

list data

[!NOET|label:references:]

  • find the first data in table/collection

    db_name> db.collection.findOne()
  • list all data in table/collection

db_name> printjson( db.getCollection('jobs').find().toArray() )

# or
db_name> db.collection.find().pretty()
# or
db_name> db.collection.find().toArray()
  • get count

    db_name> db.collection.countDocuments()
    19
    
    # or
    db_name> db.collection.estimatedDocumentCount()
    19
  • data size

    db_name> db.collection.dataSize()
    5068

query

[!NOTE|label:references:]

  • find data by _id

    db_name> db.collection.distinct('_id')
    [
      ObjectId('6544a0a06bdbf57e9914b1cd'),
      ObjectId('6544a3a5ba2f29b94c8eb4b1'),
      ObjectId('65450b1a715f2a7eb0c95658')
    ]
    
    # or
    db_name> db.collection.find({},{_id:1})
    [
      { _id: ObjectId('6544a0a06bdbf57e9914b1cd') },
      { _id: ObjectId('6544a3a5ba2f29b94c8eb4b1') },
      { _id: ObjectId('65450b1a715f2a7eb0c95658') }
    ]
    
    # or
    db_name> db.collection.find( {}, {_id:1} ).map( function(item){ return item._id; } )
    
    # or
    db_name> db.collection.find( {}, {_id:1} ).map( x => x._id )
    
    # or: https://stackoverflow.com/a/28389836/2940319
    db_name> db.runCommand ( { distinct: "collection", key: "_id" } )
    
    # or
    db_name> var arr=[]
    db_name> db.collection.find( {},{_id:1} ).forEach( function(doc){arr.push(doc._id)} )
    db_name> printjson( arr )
  • list 2 columns

    db_name> db.collection.find({},{_id:1, timestamp:1}).pretty()
    
    # or
    db_name> db.collection.find({},{_id:1, timestamp:1}).toArray()
    
    # or
    db_name> printjson(db.collection.find({}, {_id:1, user:2}))
  • query fiels in conditions

    [!NOTE|label:references:]

    db_name> db.collection.find({user: 'Marslo Jiao'}, {_id:1, timestamp:2}).pretty()
    [
      {
        _id: ObjectId('66a14d301ce9a4bb04e8c2e1'),
        timestamp: '2024-07-24 11:51:28 PDT'
      },
      {
        _id: ObjectId('66a161038305d663fb9f6f0f'),
        timestamp: '2024-07-24 13:16:03 PDT'
      }
    ]
    
    # or
    db_name> db.collection.find({user: 'Marslo Jiao'}, {_id:1, timestamp:2}).toArray()
    [
      {
        _id: ObjectId('66a14d301ce9a4bb04e8c2e1'),
        timestamp: '2024-07-24 11:51:28 PDT'
      },
      {
        _id: ObjectId('66a161038305d663fb9f6f0f'),
        timestamp: '2024-07-24 13:16:03 PDT'
      }
    ]
  • query in multiple values

    db_name> db.log_dashboard_docker.find( {'user': {$in: ['Marslo Jiao', 'John Doe']}}, {_id:1, timestamp:2} )

get key name

[!NOTE|label:references:]

db_name> var arr=[]
db_name> db.collection.find().forEach(function(doc){Object.keys(doc).forEach(function(key){arr[key]=1})})
db_name> arr
[
  _id: 1,
  user: 1,
  update_details: 1,
  timestamp: 1
]

# or
db_name> doc = db.collection.findOne();
db_name> for ( key in doc ) print( key )
_id
user
update_details
timestamp

operation

comparison operators

[!NOTE|label:references:]

OPERATORDESCRIPTION

$eq

equal (=)

$gt

greater than >

$gte

greater or equal than (>=)

$in

in (in)

$lt

less than (<)

$lte

less or equal than (<=)

$ne

not equal ()

$nin

not in (not in )

Last updated