【问题标题】:using findAndModify in mongodb using grails gorm使用 grails gorm 在 mongodb 中使用 findAndModify
【发布时间】:2012-12-23 13:42:53
【问题描述】:

我需要在带有 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();
}

它工作成功。但是现在我想在没有本机 mongodb 对象的情况下使用 findAndModify,并使用 GORM。 这项工作有什么解决办法吗?

【问题讨论】:

    标签: mongodb grails grails-orm findandmodify


    【解决方案1】:

    没有原生 API 就无法实现这一点,但是您可以像这样编写更紧凑的代码:

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

    【讨论】:

      【解决方案2】:

      使用数据库配置配置您的 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)
      ....
      

      【讨论】:

      • 不,通过使用 findAndModify,我确信可以进行 atmic 插入。此外,它通过一个查询完成,在您的代码中有两个对 DB 的查询。对我没用。
      • 好的,但是在 Gorm 中并没有所谓的 findAndModify 操作。
      • 你知道如何使用 gorm 进行原生查询吗?也许我可以在 gorm 中使用本机查询进行 findAndModify。
      • 不,我不知道。如果你真的想要原子操作,你可以使用你当前的代码。
      猜你喜欢
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      相关资源
      最近更新 更多