Uploaded image for project: 'Java Driver'
  1. Java Driver
  2. JAVA-29

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

    XMLWordPrintableJSON

Details

    • Icon: Improvement Improvement
    • Resolution: Done
    • Icon: Minor - P4 Minor - P4
    • 0.9
    • 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)

      { 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")); }

      Attachments

        Activity

          People

            eliot Eliot Horowitz (Inactive)
            jmsachs Jason Sachs
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: