MongoDB Grails 插件 ObjectId V.S.字符串编号

标签 mongodb grails groovy mongodb-java

我有一个关于 grails 的 MongoDB id 的问题。我在域类中使用了字符串 id,它会在域类中创建字符串 id,这很好。但是当我手动在 mongodb 中插入条目时(运行 db.Things.insert()),它会为新条目创建一个 ObjectId(不是字符串),我想知道我们如何解决这个问题。

谢谢!

最佳答案

引用来自:Mongo Collections - Reference Documentation

By default in GORM entities are supplied with an integer-based identifier. So for example the following entity: class Person {} Has a property called id of type java.lang.Long. In this case GORM for Mongo will generate a sequence based identifier using the technique described in the Mongo documentation on Atomic operations.

However, sequence based integer identifiers are not ideal for environments that require sharding (one of the nicer features of Mongo). Hence it is generally advised to use either String based ids:

class Person { String id } Or a native BSON ObjectId:

import org.bson.types.ObjectId class Person { ObjectId id }

BSON ObjectId instances are generated in a similar fashion to UUIDs.


因此,您应该使用 org.bson.types.ObjectId 替换您的域类的 id

关于MongoDB Grails 插件 ObjectId V.S.字符串编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15479105/

相关文章:

arrays - Mongodb Node.js 组织数组结果

php_ini 未设置为 php.ini 位置

mongodb - Docker/Mongodb 数据不持久

security - 在 Groovy 动态 SQL 中检测 SQL 注入(inject)

jenkins - Artifactory - 使用 Jenkins Pipeline 脚本上传

java - Spock 测试私有(private)方法时出现错误?

node.js - 如何检查 Mongo 的 $addToSet 是否重复

grails - 使用多个belongsTo,但一次只有一个

grails - g :select disabled property doesn't work properly

angularjs - 如何在Grails 2.5.3中使用ng-file-upload