(Quick Reference)

10 Using the MongoDB Driver Directly

Version: 2023.3.0

10 Using the MongoDB Driver Directly

A lower level API is provided by the plugin via the MongoDB driver

There is an excellent tutorial on how to use the MongoDB Java driver’s API directly in the MongoDB documentation

An example can be seen below:

// Get a db reference in the old fashion way
def db = mongo.getDatabase("mydb")

// Insert a document
db.languages.insert([name: 'Groovy'])
// A less verbose way to do it
db.languages.insert(name: 'Ruby')
// Yet another way
db.languages << [name: 'Python']

// Insert a list of documents
db.languages << [[name: 'Javascript', type: 'prototyped'], [name: 'Ioke', type: 'prototyped']]

To get hold of the mongo instance (which is an instance of the com.mongodb.Mongo class) inside a controller or service simple define a mongo property:

def mongo
def myAction = {
    def db = mongo.getDatabase("mongo")
    db.languages.insert([name: 'Groovy'])
}

A request scoped bean is also available for the default database (typically the name of your application, unless specified by the databaseName config option, plus the suffix "DB").

def peopleDB
def myAction = {
    peopleDB.languages.insert([name: 'Fred'])
}

Each domain class you define also has a collection property that allows easy access to the underlying Collection instance:

Person.collection.count() == 1
Person.collection.findOne(firstName:"Fred").lastName == "Flintstone"

You can easily convert from a native MongoDB Document into an entity using a cast:

def fred = Person.collection.findOne(firstName:"Fred") as Person