BAEL-4889: checking whether a field exists or not in MongoDB (#11129)

* BAEL-4889: checking whether a field exists or not in MongoDB

* BAEL-4889: fixed test class name

* BAEL-4889: upgraded mongo version

* BAEL-4889: changed test class name
This commit is contained in:
Maciej Główka 2021-08-24 04:44:47 +02:00 committed by GitHub
parent 22e6245c81
commit 8f6869a4b7
2 changed files with 51 additions and 1 deletions

View File

@ -33,7 +33,7 @@
</dependencies>
<properties>
<mongo.version>3.10.1</mongo.version>
<mongo.version>3.12.1</mongo.version>
<flapdoodle.version>1.11</flapdoodle.version>
<morphia.version>1.5.3</morphia.version>
</properties>

View File

@ -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<Document> 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);
}
}