Details
-
Improvement
-
Resolution: Done
-
Minor - P4
-
None
-
None
-
None
Description
Just some food for thought. DBCursor implements Iterator<DBObject> but not Iterable<DBObject> so cannot directly be used in a for loop. Consider implementing Iterable<DBObject> as well, and add its one method perhaps as follows:
@Override public Iterator<DBObject> iterator() {
return this.copy();
// outgoing copy() might not be necessary (you could just "return this;") but just to be safe
}
This allows the syntax
DBCursor cursor = db.find(query);
for (DBObject object : cursor)
{
// do something with "object"
}
or even
for (DBObject object : db.find(query))
{
// do something with "object"
}
It's only a minor convenience over
DBCursor cursor = db.find(query);
while (cursor.hasNext())
{
DBObject object = cursor.next();
// do something with "object"
}
but makes loop code just a bit more clear.
I'm getting around this by making my own wrapper class:
static public class CursorWrapper implements Iterable<DBObject>
{
private final DBCursor cursor;
private CursorWrapper(DBCursor cursor)
static public CursorWrapper wrap(DBCursor cursor)
{ return new CursorWrapper(cursor.copy()); // incoming copy() might not be necessary, but just to be safe }@Override public Iterator<DBObject> iterator()
{ return this.cursor.copy(); // outgoing copy() might not be necessary, but just to be safe }
}
and then can do
for (DBObject obj : CursorWrapper.wrap(coll.find().limit(100)))
{ System.out.println(obj.get("metadata")); }