facilitate use of "for (X x : collection)" syntax with DBCursor

XMLWordPrintableJSON

    • Type: Improvement
    • Resolution: Done
    • Priority: Minor - P4
    • 0.9
    • Affects Version/s: None
    • Component/s: None
    • None
    • None
    • None
    • None
    • None
    • None
    • None
    • None

      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)

      { this.cursor = 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")); }

            Assignee:
            Eliot Horowitz (Inactive)
            Reporter:
            Jason Sachs
            None
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved: