For the most recent version of the reference documentation, see our MongoDB Java Driver documentation site.
- MongoDB Driver
- Run Commands
Not all commands have a specific helper. However you can run any MongoDB command by using the MongoDatabase’s
The example below requires a
restaurantscollection in the
testdatabase. To create and populate the collection, follow the directions in github.
Include the following import statements:
import com.mongodb.client.MongoClients; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoDatabase; import org.bson.Document;
Connect to a MongoDB Deployment
Connect to a MongoDB deployment and declare and define a
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
MongoClient mongoClient = MongoClients.create(); MongoDatabase database = mongoClient.getDatabase("test");
For additional information on connecting to MongoDB, see Connect to MongoDB.
To run a command, construct a
object that specifies the command and pass it to the
The following runs the
buildInfo command and the
Document buildInfoResults = database.runCommand(new Document("buildInfo", 1)); System.out.println(buildInfoResults.toJson()); Document collStatsResults = database.runCommand(new Document("collStats", "restaurants")); System.out.println(collStatsResults.toJson());
For a list of available MongoDB commands, see MongoDB commands.