Skip to content

Commit 700da1a

Browse files
Daniel Kunnatherh
authored andcommitted
Updated DB API to include method to check for the existence of collections without creating a new one automatically. DBTest was modified to test this behavior.
1 parent b547174 commit 700da1a

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

src/main/com/mongodb/DB.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,29 @@ public Set<String> getCollectionNames()
215215
return new OrderedSet<String>(tables);
216216
}
217217

218+
/**
219+
* Checks to see if a collection by name %lt;name&gt; exists.
220+
* @param collectionName The collection to test for existence
221+
* @return false if no collection by that name exists, true if a match to an existing collection was found
222+
*/
223+
public boolean collectionExists(String collectionName)
224+
{
225+
if (collectionName == null || "".equals(collectionName))
226+
return false;
227+
228+
Set<String> collections = getCollectionNames();
229+
if (collections.size() == 0)
230+
return false;
231+
232+
for (String collection : collections)
233+
{
234+
if (collectionName.equalsIgnoreCase(collection))
235+
return true;
236+
}
237+
238+
return false;
239+
}
240+
218241

219242
/** Returns the name of this database.
220243
* @return the name

src/test/com/mongodb/DBTest.java

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,28 @@ public void testCreateCollection() {
7171
assertEquals(0, 1);
7272
}
7373

74+
@Test(groups = {"basic"})
75+
public void testForCollectionExistence()
76+
{
77+
_db.getCollection( "foo1" ).drop();
78+
_db.getCollection( "foo2" ).drop();
79+
_db.getCollection( "foo3" ).drop();
80+
_db.getCollection( "foo4" ).drop();
81+
82+
assertFalse(_db.collectionExists( "foo1" ));
83+
84+
BasicDBObject o1 = new BasicDBObject("capped", false);
85+
DBCollection c = _db.createCollection("foo1", o1);
86+
87+
assertTrue(_db.collectionExists( "foo1" ), "Collection 'foo' was supposed to be created, but 'collectionExists' did not return true.");
88+
assertTrue(_db.collectionExists( "FOO1" ));
89+
assertTrue(_db.collectionExists( "fOo1" ));
90+
91+
_db.getCollection( "foo1" ).drop();
92+
93+
assertFalse(_db.collectionExists( "foo1" ));
94+
}
95+
7496
/*public static class Person extends DBObject {
7597
7698
public Person(){

0 commit comments

Comments
 (0)