I am trying to insert a document with a sequence number, in one transaction, from java.
Something similar to this:
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true
}
);
return ret.seq;
}
collection.insert({
number: getNextSequence("userid"),
name: "Some Name"
});
Is it possible to do this from java? Preferably with the official java driver.
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:
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 andreturnNew
boolean (which has to be set totrue
).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.
You cannot perform this in one transaction, and even your javascript example performs a findAndModify before performing the insert.
If you're looking to insert documents into a collection with an increasing count of documents from that collection you can use the count method and add 1.
Or by using a separate "counters" collection with a findAndModify() in lieu of count()
Try this:
just as Alex wrote but this code is appropriate for 3.x versions