简体   繁体   中英

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?

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] ])

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)
....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM