Sử dụng Tạo trường trình tự tăng dần tự động trước tiên, bạn nên tạo bộ sưu tập bằng trình bao mongoDB và bộ sưu tập phải như sau:
db.counters.insert(
{
_id: "userid",
seq: 0
})
Vì vậy, bạn nhận được counters các bộ sưu tập chứa trường như _id,seq , bây giờ hãy tạo getNextSequence hàm trong java và hàm này có tham số userid dưới dạng chuỗi nên getNextSequence chức năng như thế này:
public static Object getNextSequence(String name) throws Exception{
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// Now connect to your databases
DB db = mongoClient.getDB("demo");
DBCollection collection = db.getCollection("counters");
BasicDBObject find = new BasicDBObject();
find.put("_id", name);
BasicDBObject update = new BasicDBObject();
update.put("$inc", new BasicDBObject("seq", 1));
DBObject obj = collection.findAndModify(find, update);
return obj.get("seq");
}
Hàm trên trả về seq đếm và sử dụng hàm này trong main phương pháp như sau:
public static void main(String[] args) throws Exception {
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// Now connect to your databases
DB db = mongoClient.getDB("demo");
DBCollection collection = db.getCollection("counters");
BasicDBObject document = new BasicDBObject();
document.put("_id", getNextSequence("userid"));
document.put("name","Sarah C.");
collection.insert(document); // insert first doc
document.put("_id", getNextSequence("userid"));
document.put("name", "Bob D.");
collection.insert(document); // insert second doc
}
Hiện có trong counters bộ sưu tập chứa ba tài liệu chứa name với tư cách là Sarah C. and Bob D. tương ứng và một tài liệu mặc định mà chúng tôi đã chèn thủ công vào lần đầu tiên và nó tăng dần seq như thế này { "_id" : "userid", "seq" : 2 }