book
  • README
  • cheatsheet
    • bash
      • builtin
      • syntactic sugar
      • cmd
      • havefun
    • text-processing
      • awk
      • sed
      • html
      • json
      • regex
      • unicode
    • osx
    • curl
    • tricky
    • widget
    • proxy
    • colors
    • math
    • media
    • ssl
      • keystore
      • verification
      • server
      • client
      • tricky
    • windows
      • powershell
      • choco
      • wsl
      • wt
      • shortcut
      • clsid
      • env
      • shell:folder
  • vim
    • nvim
    • install
    • color
    • plugins
      • usage
      • other plugins
      • deprecated
    • tricky
    • viml
    • windows
    • troubleshooting
  • devops
    • admin tools
    • ssh
    • git
      • config
      • alias
      • submodule
      • eol
      • example
      • gerrit
        • gerrit API
      • github
      • troubleshooting
      • tricky
      • statistics
    • pre-commit
    • release-tools
    • tmux
      • cheatsheet
    • ansible
    • vault
    • artifactory
      • api
      • cli
      • aql
      • nginx cert
    • klocwork
      • kwadmin
      • kwserver
      • api
      • q&a
    • elk
    • mongodb
    • android
    • mobile
  • jenkins
    • config
      • windows
    • appearance
    • troubleshooting
    • jenkinsfile
      • utility
      • parallel
      • build
      • envvar
      • properties
      • trigger
      • node
    • script
      • job
      • build
      • stage
      • agent
      • security & authorization
      • exception
      • monitor
      • tricky
    • api
      • blueocean
    • cli
    • plugins
      • kubernetes
      • docker
      • shared-libs
      • lockable-resource
      • ansicolor
      • badge
      • groovy-postbuild
      • simple-theme
      • customizable-header
      • artifactory
      • jira-steps
      • job-dsl
      • build-timeline
      • crumbIssuer
      • coverage
      • uno-choice
      • tricky
  • virtualization
    • kubernetes
      • init
        • kubespray
        • kubeadm
          • environment
          • crio v1.30.4
          • docker v1.15.3
          • HA
        • addons
        • etcd
      • kubectl
        • pod
        • deploy
        • replicasets
        • namespace
        • secrets
      • node
      • certificates
      • events
      • kubeconfig
      • kubelet
      • troubleshooting
      • cheatsheet
      • auth
      • api
      • tools
        • monitor
        • helm
        • network
        • minikube
    • docker
      • run & exec
      • voume
      • remove
      • show info
      • dockerfile
      • dockerd
      • tricky
      • troubleshooting
      • windows
    • crio
    • podman
  • ai
    • prompt
  • osx
    • apps
      • init
      • brew
    • defaults
    • system
    • network
    • script
    • tricky
  • linux
    • devenv
    • util
      • time & date
      • output formatting
      • params
      • tricky
    • nutshell
    • disk
    • network
    • troubleshooting
    • system
      • apt/yum/snap
      • authorization
      • apps
      • x11
    • ubuntu
      • systemctl
      • x
    • rpi
  • programming
    • groovy
    • python
      • config
      • basic
      • list
      • pip
      • q&a
    • others
    • archive
      • angular
      • maven
      • mysql
        • installation
        • logs
      • ruby
        • rubyInstallationQ&A
  • tools
    • fonts
    • html & css
    • Jira & Confluence
    • node & npm
      • gitbook
      • hexo
      • github.page
      • code themes
    • app
      • microsoft office
      • vscode
      • virtualbox
      • iterm2
      • browser
      • skype
      • teamviewer
      • others
  • quotes
  • english
Powered by GitBook
On this page
  • mongosh
  • install
  • configure
  • --eval
  • interactive mode
  • operation

Was this helpful?

  1. devops

mongodb

PreviouselkNextandroid

Last updated 9 months ago

Was this helpful?

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:]

    • windows: mongosh.cfg same directory as mongosh.exe

    • osx:

      • /usr/local/etc/mongosh.conf

      • /opt/homebrew/etc/mongosh.conf

      • /etc/mongosh.conf

    • linux: /etc/mongosh.conf

# 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 SYSTEM
    PATH

    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 SYSTEM
    PATH

    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()
  • [!NOTE|label:references:]

    db_name> db = db.getSiblingDB('db_name')

show all tables

[!NOTE|label:references:]

db_name> db.getCollectionNames()

# or
db_name> show tables

# or
db_name> show collections
  • 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:]

OPERATOR
DESCRIPTION

$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 )

Troubleshoot Connection Issues
* Collection Methods
mongodb-js/mongosh
Welcome to MongoDB Shell (mongosh)
Install mongosh
Configure mongosh
Configure Settings Using a Configuration File
Execute Code From a Configuration File
Configure Settings
config.set
Printing Mongo query output to a file while in the mongo shell
Customize the mongosh Prompt
Retrieve Shell Logs
Run Commands
Collection Methods
mongosh Methods
Methods
Options
Connect to a Deployment
Connect via mongosh
mongosh Help
EDITOR
equivalent for "use db_name"
Specify which database to use in mongodb .js script
Script Does Not Include Connection Details
db.getSiblingDB(<database>)
How can I list all collections in the MongoDB shell?
fileter tables
How can I get all the doc ids in MongoDB?
How can I get all the doc ids in MongoDB?
Query an Array
List all values of a certain field in mongodb
Return only one field from MongoDB query
Search multiple fields for multiple values in MongoDB
Get names of all keys in the collection
How to use comparison operators in MongoDB?
mongosh
install
configure
config.set
Customize the mongosh Prompt
auto-completion
local files
--eval
execute command
eval command and show as json format
interactive mode
connect to remote server
utility
show all tables
list data
query
get key name
operation
comparison operators