diff --git a/persistence-modules/java-mongodb/pom.xml b/persistence-modules/java-mongodb/pom.xml index 15d904b12c..f708a54f46 100644 --- a/persistence-modules/java-mongodb/pom.xml +++ b/persistence-modules/java-mongodb/pom.xml @@ -33,7 +33,7 @@ - 3.10.1 + 3.12.1 1.11 1.5.3 diff --git a/persistence-modules/java-mongodb/src/test/java/com/baeldung/existence.field/FieldExistenceLiveTest.java b/persistence-modules/java-mongodb/src/test/java/com/baeldung/existence.field/FieldExistenceLiveTest.java new file mode 100644 index 0000000000..ca37ac6664 --- /dev/null +++ b/persistence-modules/java-mongodb/src/test/java/com/baeldung/existence.field/FieldExistenceLiveTest.java @@ -0,0 +1,50 @@ +package com.baeldung.existence.field; + +import com.mongodb.BasicDBObject; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.Filters; +import org.bson.Document; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class FieldExistenceLiveTest { + private MongoClient mongoClient; + private MongoDatabase db; + private MongoCollection collection; + + @Before + public void setup() { + if (mongoClient == null) { + mongoClient = new MongoClient(); + db = mongoClient.getDatabase("existence"); + collection = db.getCollection("users"); + collection.insertOne(Document.parse("{'name':'Ben','surname': 'Big'}")); + } + } + + @Test + public void givenMongoCollection_whenUsingFilters_thenCheckingForExistingFieldWorks() { + Document nameDoc = collection.find(Filters.exists("name")).first(); + assertNotNull(nameDoc); + assertFalse(nameDoc.isEmpty()); + + nameDoc = collection.find(Filters.exists("non_existing")).first(); + assertNull(nameDoc); + } + + @Test + public void givenMongoCollection_whenUsingStandardDocumentQuery_thenCheckingForExistingFieldWorks() { + Document query = new Document("name", new BasicDBObject("$exists", true)); + Document doc = collection.find(query).first(); + assertNotNull(doc); + assertFalse(doc.isEmpty()); + + query = new Document("non_existing", new BasicDBObject("$exists", true)); + doc = collection.find(query).first(); + assertNull(doc); + } +}