zorro6064
zorro6064

Reputation: 484

using findAndModify in mongodb using grails gorm

I need to use findAndModify in my application with grails and mongoDB. I used this code :

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();
}

and it work successful. But now I want use findAndModify without native mongodb object, and with using GORM. Is there any solution for this work?

Upvotes: 1

Views: 921

Answers (2)

fabiangebert
fabiangebert

Reputation: 2623

There is not way to accomplish this without native API, you can however write your code a bit more compact like this:

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

Upvotes: 3

coderLMN
coderLMN

Reputation: 3076

Config your DataSource.groovy with db configurations.

Then define a Domain class:

Class Seq{

    int seq

}

And use dynamic finder in a sevice:

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
    }
}

Then make a call when you need that action:

def seqService

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

Upvotes: 0

Related Questions