Home > Software design >  Check if Document in MongoDB exists, using reactive-streams
Check if Document in MongoDB exists, using reactive-streams

Time:01-25

I'm trying to check if a document already exits, but I'm having some problems. I tried different solutions:

  1. Using findOne() and checking if output is null (doesn’t work)
  2. Using countDocument() (doesn’t work) The error that is saw the most is that I can’t cast for example: Publisher to long or Publisher to Document

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");
}

CodePudding user response:

To check if a document exists you can use the exists() method from the ReactiveMongoTemplate class. The method takes a Query object as its parameter, which is used to specify the conditions to match the document. You can read about the exists() method right here.

Here is an example of how you can use the exists() method to check if a document with a specific id field exists in a collection called docs:

Query query = new Query(Criteria.where("id").is("unique-id-123"));
Mono<Boolean> exists = reactiveMongoTemplate.exists(query, “docs”);

Where query is org.springframework.data.mongodb.core.query.Query and reactiveMongoTemplate is org.springframework.data.mongodb.core.ReactiveMongoTemplate


Another solutions that you mentioned actually have to work too, for example:

  1. Using findOne() method:
Query query = new Query(Criteria.where("id").is("unique-id-123"));
Mono<Document> documentMono = reactiveMongoTemplate.findOne(query, Document.class, "docs");
documentMono.subscribe(doc -> {
    if (doc != null) {
        System.out.println("Document exists!");
    } else {
        System.out.println("Document does not exist!");
    }
});

You can read about findOne() method here.

  1. Using count() method:
Query query = new Query(Criteria.where("id").is("unique-id-123"));
Mono<Long> count = reactiveMongoTemplate.count(query, "docs");
count.subscribe(cnt -> {
    if (cnt > 0) {
        System.out.println("Document exists!");
    } else {
        System.out.println("Document does not exist!");
    }
});

You can read about count() method here

  • Related