使用grails gorm在mongodb中使用findAndModify

时间:2012-12-23 13:42:53

标签: mongodb grails gorm findandmodify

我需要在grails和mongoDB的应用程序中使用findAndModify。 我用了这段代码:

public static String getNextId(DB db, String seq_name) {
String sequence_collection = "seq"; // the name of the sequence collection
String sequence_field = "seq"; // the name of the field which holds the sequence

DBCollection seq = db.getCollection(sequence_collection); // get the collection (this will create it if needed)

// this object represents your "query", its analogous to a WHERE clause in SQL
DBObject query = new BasicDBObject();
query.put("_id", seq_name); // where _id = the input sequence name

// this object represents the "update" or the SET blah=blah in SQL
DBObject change = new BasicDBObject(sequence_field, 1);
DBObject update = new BasicDBObject("$inc", change); // the $inc here is a mongodb command for increment

// Atomically updates the sequence field and returns the value for you
DBObject res = seq.findAndModify(query, new BasicDBObject(), new BasicDBObject(), false, update, true, true);
return res.get(sequence_field).toString();
}

它运作成功。但现在我想使用findAndModify而不使用本机mongodb对象,并使用GORM。 这项工作有什么解决方案吗?

2 个答案:

答案 0 :(得分:3)

如果没有本机API,就没有办法实现这一点,但是你可以像这样编写更紧凑的代码:

def collection = Seq.collection
collection.findAndModify([_id: seq_name ], [ "\$inc": [seq:1] ])

答案 1 :(得分:0)

使用db配置配置DataSource.groovy。

然后定义一个Domain类:

Class Seq{

    int seq

}

在服务中使用动态查找器:

Class SeqService {

    String findAndModify(String seq_name) {
        def seqInstance = Seq.get(seq_name)
        if(seqInstance){
            seqInstance.seq ++
            seqInstance.save()
            return seqInstance.seq.toString()
        }
        return ''      //instance not found
    }
}

然后在需要采取行动时拨打电话:

def seqService

def id
.......
def result = seqService.findAndModify(id)
....