Badmiral
Badmiral

Reputation: 1589

mongodb java check if insert succeeded

MongoClient mongoClient = new MongoClient()
DB db = mongoClient.getDB("mydb")
DBCollection recordsColl = db.getCollection("records")
BasicDBObject mongoRecord = new BasicDBObject()
//put some things in mongoRecord
recordsColl.insert(mongoRecord)

How can I tell if the insert went successfully? Doing

WriteResult writeResult = recordsColl.insert(mongoRecord)
writeResult.getLastError()

Seems getLastError() has depreciated. Any suggestions? Thanks!

Upvotes: 2

Views: 1883

Answers (1)

Markus W Mahlberg
Markus W Mahlberg

Reputation: 20703

You can easily achieve that by setting the write concern to an appropriate level. By doing sth like

mongoClient.setWriteConcern(WriteConcern.SAFE);

before the write operation, an exception will be raised in case the write wasn't successful. Have a look at the Java driver docs for details.

Upvotes: 1

Related Questions