MongoUtils { static boolean isCollectionEmpty(@NotNull MongoCollection<?> collection, @Nullable ClientSession session) { MongoCollection<?> c = collection.withReadPreference(ReadPreference.primary()); FindIterable<BasicDBObject> result; if (session != null) { result = c.find(session, BasicDBObject.class); } else { result = c.find(BasicDBObject.class); } return result.limit(1).first() == null; }    }
@Test public void isCollectionEmpty() { MongoConnection c = connectionFactory.getConnection(); assertNotNull(c); c.getDatabase().drop(); String collectionName = Collection.NODES.toString(); MongoStatus status = new MongoStatus(c.getMongoClient(), c.getDBName()); MongoCollection<BasicDBObject> nodes = c.getDatabase() .getCollection(collectionName, BasicDBObject.class); assertTrue(MongoUtils.isCollectionEmpty(nodes, null)); if (status.isClientSessionSupported()) { try (ClientSession s = c.getMongoClient().startSession()) { assertTrue(MongoUtils.isCollectionEmpty(nodes, s)); } } nodes.insertOne(new BasicDBObject("p", "v")); assertFalse(MongoUtils.isCollectionEmpty(nodes, null)); if (status.isClientSessionSupported()) { try (ClientSession s = c.getMongoClient().startSession()) { assertFalse(MongoUtils.isCollectionEmpty(nodes, s)); } } nodes.deleteMany(new BasicDBObject()); assertTrue(MongoUtils.isCollectionEmpty(nodes, null)); if (status.isClientSessionSupported()) { try (ClientSession s = c.getMongoClient().startSession()) { assertTrue(MongoUtils.isCollectionEmpty(nodes, s)); } } }