sql >> Base de Datos >  >> NoSQL >> MongoDB

¿Cómo consultar mongodb desde groovy/grails?

Suponiendo que haya agregado la dependencia del controlador mongodb java en la configuración de compilación y haya actualizado sus dependencias.

Cree un servicio de griales llamado MongoService.groovy y pon el siguiente código.

No olvides importar mongodb

package com.organisation.project

import com.mongodb.*


class MongoService {
    private static MongoClient mongoClient
    private static host = "localhost"    //your host name
    private static port = 27017      //your port no.
    private static databaseName = "your-mongo-db-name"

    public static MongoClient client() {
        if(mongoClient == null){
            return new MongoClient(host,port)
        }else {
            return mongoClient
        }
    }

    public DBCollection collection(collectionName) {
        DB db = client().getDB(databaseName)
        return db.getCollection(collectionName)
    }
}

Ahora podemos usar este MongoService en nuestros controladores u otros servicios.

Ahora puedes hacer lo siguiente en tu controlador.

No olvides importar mongodb.DBCursor

package com.organisation.project



import com.mongodb.DBCursor

class YourControllerOrService {

    def mongoService    //including Mongo service 

    def method(){
        def collection = mongoService.collection("your-collection-name")
        DBCursor cursor =  collection.find()
        try{
            while(cursor.hasNext()){
                def doc = cursor.next()
                println doc     //will print raw data if its in your database for that collection
                }

         }finally {
                  cursor.close()
         }

    }
}

Para obtener más información, consulte mongodb java docs