I am trying to insert a document with a sequence number, in one transaction, from java.
Something similar to this:
function getNextSequence(name) {
Following the documentation for creating an Auto-Incrementing Sequence Field, we adapt it to be used in Java with the Java MongoDB driver.
Example implementation:
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
public class TestAutoIncrement {
private final static String DB_NAME = "MyTestDB";
private final static String TEST_COLLECTION = "testCollection";
private final static String COUNTERS_COLLECTION = "countersCollection";
public static DBCollection testCollection;
public static DBCollection countersCollection;
public static void main(String[] args) {
try {
MongoClient mongoClient = new MongoClient();
DB database = mongoClient.getDB(DB_NAME);
testCollection = database.getCollection(TEST_COLLECTION);
countersCollection = database.getCollection(COUNTERS_COLLECTION);
} catch (UnknownHostException e) {
e.printStackTrace();
}
if (countersCollection.count() == 0) {
createCountersCollection();
}
createTestCollection();
}
public static void createCountersCollection() {
BasicDBObject document = new BasicDBObject();
document.append("_id", "userid");
document.append("seq", 0);
countersCollection.insert(document);
}
public static Object getNextSequence(String name) {
BasicDBObject searchQuery = new BasicDBObject("_id", name);
BasicDBObject increase = new BasicDBObject("seq", 1);
BasicDBObject updateQuery = new BasicDBObject("$inc", increase);
DBObject result = countersCollection.findAndModify(searchQuery, null, null,
false, updateQuery, true, false);
return result.get("seq");
}
public static void createTestCollection() {
BasicDBObject document = new BasicDBObject();
document.append("_id", getNextSequence("userid"));
document.append("name", "Sarah");
testCollection.insert(document);
document = new BasicDBObject();
document.append("_id", getNextSequence("userid"));
document.append("name", "Bob");
testCollection.insert(document);
document = new BasicDBObject();
document.append("_id", getNextSequence("userid"));
document.append("name", "Alex");
testCollection.insert(document);
}
}
Special attention must be paid to the findAndModify
method. In the Java MongoDB driver (2.12.4), the method is available with 4 different signatures.
You must use one which lets you pass a query
object, update
object and returnNew
boolean (which has to be set to true
).
That's because, according to documentation:
By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option.
We need to return the document with the modifications made on the update.