Run Commands
Not all database commands have a specific helper method. However, you can
run any MongoDB command by using the MongoDatabase.runCommand()
method.
To learn more about MongoDB commands, see Database Commands in the Server manual.
Prerequisites
You must set up the following components to run the code examples in this guide:
A
test.restaurants
collection populated with documents from therestaurants.json
file in the documentation assets GitHub.The following import statements:
import org.mongodb.scala._
Note
This guide uses the Observable
implicits as covered in the
Quick Start Primer.
Connect to a MongoDB Deployment
First, connect to a MongoDB deployment, then declare and define
a MongoDatabase
instance.
The following code connects to a standalone
MongoDB deployment running on localhost
on port 27017
. Then, it
defines the database
variable to refer to the test
database:
val mongoClient: MongoClient = MongoClient() val database: MongoDatabase = mongoClient.getDatabase("test")
To learn more about connecting to MongoDB deployments, see the Connect to MongoDB guide.
Run the buildInfo Command
To run the buildInfo
command, construct a Document
object that
specifies the command and pass it as a parameter to the runCommand()
method.
The following sample code runs the buildInfo
command and prints
the results:
database.runCommand(Document("buildInfo" -> 1)).printResults()
To view a list of available MongoDB commands, see Database Commands in the Server manual.