Run Commands

Not all commands have a specific helper. However you can run any MongoDB command by using the MongoDatabase’s runCommand() method.

Prerequisites

  • The example below requires a restaurants collection in the test database. To create and populate the collection, follow the directions in github.

  • Include the following import statements:

     import org.mongodb.scala._
    
important

This guide uses the Observable implicits as covered in the Quick Start Primer.

Connect to a MongoDB Deployment

Connect to a MongoDB deployment and declare and define a MongoDatabase instance.

For example, include the following code to connect to a standalone MongoDB deployment running on localhost on port 27017 and define database to refer to the test database:

val mongoClient: MongoClient = MongoClient()
val database: MongoDatabase = mongoClient.getDatabase("test")

For additional information on connecting to MongoDB, see Connect to MongoDB.

Run the buildInfo Command

To run the buildInfo command, construct a Document object that specifies the command and pass it to the runCommand() method.

The following sample code runs the buildInfo command and prints the results:

// Note: this code example uses a custom implicit helper referenced in the Quick Start Primer
database.runCommand(Document("buildInfo" -> 1)).printResults()

For a list of available MongoDB commands, see MongoDB commands.