Using the new 3.0+ java driver from mongo what is the best way to check if a document exists in a collection.
I have looked at here and tried to do something similar. I have only gotten as far as this:
FindIterable<Document> iterable = collection.find(eq("code", "abcdefg")).projection(Projections.include("_id")).limit(1);
This returns a FindIterable but how do you check it has found anything at all ? If you can please provide a code example.
I did try:
if (!iterable.first().isEmpty()){System.out.println(" RESILT IS FOUND ");}else{System.out.println(" RESULT IS NOT FOUND ");}
but when the query returns nothing it dies with the following error:
Exception in thread "main" java.lang.NullPointerException
at com.oss.niagaramqtt.MongoLib.exists(MongoLib.java:58)
at com.oss.niagaramqtt.MongoLib.<init>(MongoLib.java:47)
at com.oss.niagaramqtt.startup.main(startup.java:24)
Indeed is this the correct approach overall for checking the existence of a document?
EDIT:
This could be the answer please confirm:
MongoCursor<Document> iterable = collection.find(eq("code", "abcdefg")).projection(Projections.include("_id")).limit(1).iterator();
if (iterable.hasNext()){System.out.println(" RESILT IS FOUND ");}else{System.out.println(" RESULT IS NOT FOUND ");}
Your way is good if you need to load this document in case it exists. If you don't need to load it then you can use MongoCollection.count method like:
long count = collection.count(new BsonDocument("code", new BsonString("abcdefg")));
if (count > 0){System.out.println(" RESILT IS FOUND ");}else{System.out.println(" RESULT IS NOT FOUND ");}
[Update] In case data is stored on a sharded cluster, db.collection.count() can result in an inaccurate count if orphaned documents exist or if a chunk migration is in progress. So it's safer to use aggregate
function instead:
Iterator<Document> it = collection.aggregate(Arrays.asList(
new Document("$match", new Document("code", "abcdefg")),
new Document("$group", new Document("_id", null).append("count",
new Document("$sum", 1))))).iterator();
int count = it.hasNext() ? (Integer)it.next().get("count") : 0;
See http://docs.mongodb.org/manual/reference/sql-aggregation-comparison/ for more details.
Please check this count operation at java API 3.0 in a collection.
You can basically do:
MongoClient mongoClient2 = new MongoClient("localhost", 27017);
long count = mongoClient2.getDatabase("mongoBase")
.getCollection("collection")
.count(new Document("code", "abcdefg"));
if(count>0){
//exists
}
you will find great examples here:
https://github.com/mongodb/mongo-java-driver/tree/8866de115d45ea73a39da9360159d3fbb6390dd9/driver/src/examples/tour