MongoDB Usage - Mark-Millard/oktopus GitHub Wiki

The Oktopus Controller uses the MongoDB in a Docker container.

Docker Container

Official Docker Image: https://hub.docker.com/_/mongo

Information about Docker and MongoDB container can be found here.

mongosh

mongosh is a shell tool that can be used to inspect the DB. Documenation for this tool may be found at this location.

msm@ubuntu-22-04-lts-template:~/Projects/oktopus/deploy/compose$ mongosh
Current Mongosh Log ID:	67ad43affdff20c926544ca6
Connecting to:		mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.3.8
Using MongoDB:		8.0.4
Using Mongosh:		2.3.8

For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/

------
   The server generated these startup warnings when booting
   2025-02-12T23:13:08.986+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
   2025-02-12T23:13:10.820+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
   2025-02-12T23:13:10.821+00:00: For customers running the current memory allocator, we suggest changing the contents of the following sysfsFile
   2025-02-12T23:13:10.821+00:00: For customers running the current memory allocator, we suggest changing the contents of the following sysfsFile
   2025-02-12T23:13:10.821+00:00: We suggest setting the contents of sysfsFile to 0.
   2025-02-12T23:13:10.821+00:00: Your system has glibc support for rseq built in, which is not yet supported by tcmalloc-google and has critical performance implications. Please set the environment variable GLIBC_TUNABLES=glibc.pthread.rseq=0
   2025-02-12T23:13:10.821+00:00: vm.max_map_count is too low
   2025-02-12T23:13:10.821+00:00: We suggest setting swappiness to 0 or 1, as swapping can cause performance problems.
------

test>

mongosh Help

Use the "help" command at the "test>" prompt to list the mongosh capabilities.

test> help

  Shell Help:

    use                                        Set current database
    show                                       'show databases'/'show dbs': Print a list of all available databases.
                                               'show collections'/'show tables': Print a list of all collections for current database.
                                               'show profile': Prints system.profile information.
                                               'show users': Print a list of all users for current database.
                                               'show roles': Print a list of all roles for current database.
                                               'show log <type>': log for current connection, if type is not set uses 'global'
                                               'show logs': Print all logs.

    exit                                       Quit the MongoDB shell with exit/exit()/.exit
    quit                                       Quit the MongoDB shell with quit/quit()
    Mongo                                      Create a new connection and return the Mongo object. Usage: new Mongo(URI, options [optional])
    connect                                    Create a new connection and return the Database object. Usage: connect(URI, username [optional], password [optional])
    it                                         result of the last line evaluated; use to further iterate
    version                                    Shell version
    load                                       Loads and runs a JavaScript file into the current shell environment
    enableTelemetry                            Enables collection of anonymous usage data to improve the mongosh CLI
    disableTelemetry                           Disables collection of anonymous usage data to improve the mongosh CLI
    passwordPrompt                             Prompts the user for a password
    sleep                                      Sleep for the specified number of milliseconds
    print                                      Prints the contents of an object to the output
    printjson                                  Alias for print()
    convertShardKeyToHashed                    Returns the hashed value for the input using the same hashing function as a hashed index.
    cls                                        Clears the screen like console.clear()
    isInteractive                              Returns whether the shell will enter or has entered interactive mode

  For more information on usage: https://docs.mongodb.com/manual/reference/method

Oktopus Controller Databases

To list or show the databases, use "show dbs" in the mongo shell:

test> show dbs
account-mngr  108.00 KiB
adapter       108.00 KiB
admin          40.00 KiB
config        108.00 KiB
general        12.00 KiB
local          72.00 KiB

Display Tables or Collections

To list or show the database tables, first select the database with "use" command and then display the tables with the "show" command:

test> use adapter
switched to db adapter
adapter> show tables
devices
adapter>

Collection Help

The following mongosh command may be used to obtain help on the "devices" collection:

adapter> db.devices.help

  Collection Class:

    aggregate                                  Calculates aggregate values for the data in a collection or a view.
    bulkWrite                                  Performs multiple write operations with controls for order of execution.
    count                                      Returns the count of documents that would match a find() query for the collection or view.
    countDocuments                             Returns the count of documents that match the query for a collection or view.
    deleteMany                                 Removes all documents that match the filter from a collection.
    deleteOne                                  Removes a single document from a collection.
    distinct                                   Finds the distinct values for a specified field across a single collection or view and returns the results in an array.
    estimatedDocumentCount                     Returns the count of all documents in a collection or view.
    find                                       Selects documents in a collection or view.
    findAndModify                              Modifies and returns a single document.
    findOne                                    Selects documents in a collection or view.
    renameCollection                           Renames a collection.
    findOneAndDelete                           Deletes a single document based on the filter and sort criteria, returning the deleted document.
    findOneAndReplace                          Modifies and replaces a single document based on the filter and sort criteria.
    findOneAndUpdate                           Updates a single document based on the filter and sort criteria.
    insert                                     Inserts a document or documents into a collection.
    insertMany                                 Inserts multiple documents into a collection.
    insertOne                                  Inserts a document into a collection.
    isCapped                                   Checks if a collection is capped
    remove                                     Removes documents from a collection.
    replaceOne                                 Replaces a single document within the collection based on the filter.
    update                                     Modifies an existing document or documents in a collection.
    updateMany                                 Updates all documents that match the specified filter for a collection.
    updateOne                                  Updates a single document within the collection based on the filter.
    compactStructuredEncryptionData            Compacts structured encryption data
    convertToCapped                            calls {convertToCapped:'coll', size:maxBytes}} command
    createIndexes                              Creates one or more indexes on a collection
    createIndex                                Creates one index on a collection
    ensureIndex                                Creates one index on a collection
    getIndexes                                 Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
    getIndexSpecs                              Alias for getIndexes. Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
    getIndices                                 Alias for getIndexes. Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
    getIndexKeys                               Return an array of key patterns for indexes defined on collection
    dropIndexes                                Drops the specified index or indexes (except the index on the _id field) from a collection.
    dropIndex                                  Drops or removes the specified index from a collection.
    totalIndexSize                             Reports the total size used by the indexes on a collection.
    reIndex                                    Rebuilds all existing indexes on a collection.
    getDB                                      Get current database.
    getMongo                                   Returns the Mongo object.
    dataSize                                   This method provides a wrapper around the size output of the collStats (i.e. db.collection.stats()) command.
    storageSize                                The total amount of storage allocated to this collection for document storage.
    totalSize                                  The total size in bytes of the data in the collection plus the size of every index on the collection.
    drop                                       Removes a collection or view from the database.
    exists                                     Returns collection infos if the collection exists or null otherwise.
    getFullName                                Returns the name of the collection prefixed with the database name.
    getName                                    Returns the name of the collection.
    runCommand                                 Runs a db command with the given name where the first param is the collection name.
    explain                                    Returns information on the query plan.
    stats                                      Returns statistics about the collection.
    latencyStats                               returns the $latencyStats aggregation for the collection. Takes an options document with an optional boolean 'histograms' field.
    initializeOrderedBulkOp                    Initializes an ordered bulk command. Returns an instance of Bulk
    initializeUnorderedBulkOp                  Initializes an unordered bulk command. Returns an instance of Bulk
    getPlanCache                               Returns an interface to access the query plan cache for a collection. The interface provides methods to view and clear the query plan cache.
    mapReduce                                  Calls the mapReduce command
    validate                                   Calls the validate command. Default full value is false
    getShardVersion                            Calls the getShardVersion command
    getShardDistribution                       Prints the data distribution statistics for a sharded collection.
    watch                                      Opens a change stream cursor on the collection
    hideIndex                                  Hides an existing index from the query planner.
    unhideIndex                                Unhides an existing index from the query planner.
    analyzeShardKey                            Returns metrics for evaluating a shard key. That is, ‘key’ can be a candidate shard key for an unsharded or sharded collection, or the current shard key for a sharded collection.
    configureQueryAnalyzer                     Starts or stops collecting metrics about reads and writes against an unsharded or sharded collection.
    checkMetadataConsistency                   Returns a cursor with information about metadata inconsistencies
    getSearchIndexes                           Returns an array that holds a list of documents that identify and describe the existing search indexes on the collection.
    createSearchIndex                          Creates one search indexes on a collection
    createSearchIndexes                        Creates one or more search indexes on a collection
    dropSearchIndex                            Drops or removes the specified search index from a collection.
    updateSearchIndex                          Updates the sepecified search index.

Collection Key Information

To obtain information about the Collection index keys, you can use the "getIndexKeys" and "getIndexSpecs" functions on the collection. For example:

adapter> db.devices.getIndexKeys()
[ { _id: 1 }, { sn: 1 } ]
adapter> db.devices.getIndexSpecs()
[
  { v: 2, key: { _id: 1 }, name: '_id_' },
  { v: 2, key: { sn: 1 }, name: 'sn_1', unique: true }
]

Object Query

To list the objects inserted into a Collection, use the "find" and "**findOne" functions on the collection. For example:

Controller Software

MongoDB Source

The following source directories contain the Go software implementation for the Mongo DB interface:

  • <project_dir>/backend/services/mtp/adapter/internal/db/
  • <project_dir>/backend/services/mtp/adapter/internal/reqs
  • <project_dir>/backend/services/controller/internal/db
  • <project_dir>/backend/services/controller/internal/api

MongoDB Go Driver

Oktopus Controller uses the MongoDB Go Driver library.

Package include:

  • go.mongodb.org/mongo-driver/bson
  • go.mongodb.org/mongo-driver/mongo
  • go.mongodb.org/mongo-driver/mongo/options

Resources

⚠️ **GitHub.com Fallback** ⚠️