I'm trying to check if a document already exits, but I'm having some problems. I tried different solutions:
- Using
findOne()and checking if output isnull(doesn’t work) - Using
countDocument()(doesn’t work) The error that is saw the most is that I can’t cast for example:PublishertolongorPublishertoDocument
Thanks.
Method 1:
Document d = collection.find(eq("UUID", id)).first();
if (d == null) {
System.out.println("document = null");
return;
}
System.out.println("document exists");
Method 2:
if (collection.countDocuments(query) < 1) {
System.out.println("Document exists");
}
To check if a document exists you can use the
exists()method from theReactiveMongoTemplateclass. The method takes aQueryobject as its parameter, which is used to specify the conditions to match the document. You can read about theexists()method right here.Here is an example of how you can use the
exists()method to check if a document with a specificidfield exists in a collection calleddocs:Where
queryisorg.springframework.data.mongodb.core.query.QueryandreactiveMongoTemplateisorg.springframework.data.mongodb.core.ReactiveMongoTemplateAnother solutions that you mentioned actually have to work too, for example:
findOne()method:You can read about
findOne()method here.Update for [1]: findOne():
As kerbermeister mentioned, That approach will not work:
and
count()method:You can read about
count()method here