我正在尝试在MongoDb中实现一个自动增量列
我正在关注这篇文章:mongodb_autoincrement_sequence
他说要在服务器上创建一个java脚本函数:
function getNextSequenceValue {some logic reading from a Sequence}
然后在插入文档时调用它:
>db.products.insert({
"_id":getNextSequenceValue("productid")
...
我如何使用java框架(Spring和mongoTemplate)做同样的事情?
我试图将调用添加到document.put(newDocument.id,“getNextSequenceValue ...”
但它会将实际的字符串“getNextSequenceValue ...”保存到数据库中,并且不会生成ID
DBCollection collection = mongoTemplate.getCollection(DbCollections.employee);
document.put(newDocument.id,"getNextSequenceValue(" +DbSequences.docSeqId + ")");
WriteResult result = collection.save(document);
答案 0 :(得分:0)
最终使用this
// connect to MongoDB server.
Mongo mongo = new Mongo("localhost", 27017);
DB database = mongo.getDB("mydb");
DBCollection collection = database.getCollection("testCollection");
// create a simple db object where counter value is 0
DBObject temp = new BasicDBObject("name", "someName").append("counter", 0);
// insert it into the collection
collection.insert(temp);
// create an increment query
DBObject modifier = new BasicDBObject("counter", 1);
DBObject incQuery = new BasicDBObject("$inc", modifier);
// create a search query
DBObject searchQuery = new BasicDBObject("name", "someName");
// increment a counter value atomically
WriteResult upRes = collection.update(searchQuery, incQuery);