如何从 groovy/grails 查询 mongodb? [英] How to query mongodb from groovy/grails?

查看:20
本文介绍了如何从 groovy/grails 查询 mongodb?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是否必须有一个域对象来查询 mongodb?

Do I have to have a domain object to query mongodb?

如果我只想显示一些原始数据怎么办?从我的控制器查询 mongodb 的语法是什么?

What if I just want some raw data to be displayed? What would be the syntax to query mongodb from my controller?

我试过了

"def var = db.nameOfMyCollection.find()"

但它说在我的控制器类中没有像 db 这样的属性.

but it says no such property as db in my controller class.

我知道我的应用程序正在连接到数据库,因为我正在监视 mongo server 日志,当我启动我的 grails 应用程序时,它会将连接数增加 1.

I know that my application is connecting to the database because I am monitoring mongo server log and it increases the number of connections by one when I launch my grails app.

推荐答案

假设您已经在构建配置中添加了 mongodb java 驱动程序依赖项并刷新了您的依赖项.

Assuming you have added mongodb java driver dependency in build config and refreshed your dependencies.

创建一个名为 MongoService.groovy 的 grails 服务并输入以下代码.

Create a grails service named MongoService.groovy and put the following code.

别忘了导入mongodb

Dont forget to import 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)
    }
}

我们现在可以在我们的控制器或其他服务中使用这个 MongoService.

We can now use this MongoService in our controllers or other services.

现在您可以在控制器中执行以下操作.

Now you can do following stuff in your controller.

别忘了导入 mongodb.DBCursor

Dont forget to import 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()
         }

    }
}

有关更多信息,请参阅 mongodb java 文档

For more info Refer mongodb java docs

这篇关于如何从 groovy/grails 查询 mongodb?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆