MongoUtils { static void createIndex(MongoCollection<?> collection, String field, boolean ascending, boolean unique, boolean sparse) throws MongoException { createIndex(collection, new String[]{field}, new boolean[]{ascending}, unique, sparse); }    }
@Test public void createIndex() { MongoConnection c = connectionFactory.getConnection(); assertNotNull(c); c.getDatabase().drop(); MongoCollection collection = c.getDatabase().getCollection("test"); MongoUtils.createIndex(collection, "foo", true, false, true); MongoUtils.createIndex(collection, "bar", false, true, false); MongoUtils.createIndex(collection, new String[]{"baz", "qux"}, new boolean[]{true, false}, false, false); assertTrue(MongoUtils.hasIndex(collection, "_id")); assertTrue(MongoUtils.hasIndex(collection, "foo")); assertFalse(MongoUtils.hasIndex(collection, "foo", "bar")); assertTrue(MongoUtils.hasIndex(collection, "baz", "qux")); List<Document> indexes = new ArrayList<>(); collection.listIndexes().into(indexes); assertEquals(4, indexes.size()); for (Document info : indexes) { Document key = (Document) info.get("key"); if (key.keySet().contains("foo")) { assertEquals(1, key.keySet().size()); assertEquals(1, key.get("foo")); assertEquals(Boolean.TRUE, info.get("sparse")); } else if (key.keySet().contains("bar")) { assertEquals(1, key.keySet().size()); assertEquals(-1, key.get("bar")); assertEquals(Boolean.TRUE, info.get("unique")); } else if (key.keySet().contains("baz")) { assertEquals(2, key.keySet().size()); assertEquals(1, key.get("baz")); assertEquals(-1, key.get("qux")); } } c.getDatabase().drop(); }
@Test(expected = IllegalArgumentException.class) public void checkArguments() { MongoConnection c = connectionFactory.getConnection(); assertNotNull(c); MongoCollection collection = c.getDatabase().getCollection("test"); MongoUtils.createIndex(collection, new String[]{"foo", "bar"}, new boolean[]{true}, false, true); }