import org.bson.Document;
|
|
import com.mongodb.client.MongoClients;
|
import com.mongodb.client.MongoCollection;
|
import com.mongodb.client.model.FindOneAndUpdateOptions;
|
import com.mongodb.client.model.ReturnDocument;
|
|
public class MongoFindOneAndUpdateTest {
|
|
public static void main(String[] args) {
|
// I'm running mongo 3.4 locally
|
final String connStr = "mongodb://localhost:27017/test?ssl=false";
|
final MongoCollection<Document> col = MongoClients.create(connStr)
|
.getDatabase("test").getCollection("fakeCol");
|
// Make sure we start with an empty collection
|
col.drop();
|
// insert a simple document
|
col.insertOne(new Document()
|
.append("_id", "fakeId")
|
.append("one", 1)
|
.append("foo", "bar"));
|
{
|
final Document doc = col.find().iterator().next();
|
System.out.println(doc.toJson());
|
// prints { "_id" : "fakeId", "one" : 1, "foo" : "bar" } as expected
|
}
|
{
|
// Find a document with no filter and update it with no operation,
|
// and then return the updated document, at least that's what I expected to happen.
|
final Document doc = col.findOneAndUpdate(new Document(), new Document(),
|
new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER));
|
System.out.println(doc.toJson());
|
// prints { "_id" : "fakeId" }
|
// What???
|
}
|
{
|
// Just to be sure the previous result is correct
|
final Document doc = col.find().iterator().next();
|
System.out.println(doc.toJson());
|
// prints { "_id" : "fakeId" }
|
// Yeah, the document was for some reason obliterated
|
}
|
col.drop();
|
}
|
|
}
|