1

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?

zorro6064
  • 484
  • 2
  • 7
  • 18

2 Answers2

3

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] ])
fabiangebert
  • 2,623
  • 2
  • 22
  • 25
0

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)
....
coderLMN
  • 3,076
  • 1
  • 21
  • 26
  • No, with using findAndModify, I'm sure of an atmic insertion. In addition it done with one query, in your code there is two query to DB. It isn't usefull for me. – zorro6064 Dec 24 '12 at 05:46
  • OK, but there is nothing known as findAndModify operation in Gorm. – coderLMN Dec 24 '12 at 06:13
  • Do you know how can do a native query with gorm? perhaps I could do findAndModify using native query in gorm. – zorro6064 Dec 24 '12 at 06:20
  • No, I don't. If you really want atomic operation, you can use your current code. – coderLMN Dec 24 '12 at 06:29