Search code examples
c#.netmongodbmongodb-.net-driver

Mongo cursor "freezes" so can't perform .setskip()


Compiler tells me that I cannot perform .setSkip() after a .Find() because the cursor is frozen. I understand that I can/should just create a new cursor, but my question is why does the cursor freeze after the .find()? It seems odd I can't make a query then advance the cursor.

  MongoCursor<BsonDocument> cursor;
  var query = Query.NE("OriginalMessage", "JUNK");   // get all non-junk messages
  cursor = this.untypedcollection.Find(query);
  cursor.SetSkip(20);           // fails at compile - cursor frozen

Solution

  • There's no problem in using SetSkip after a Find. Here's a working example:

    var client = new MongoClient();
    var db = client.GetServer().GetDatabase("db");
    var collection = db.GetCollection("collection");
    
    var query = Query.NE("OriginalMessage", "JUNK");
    var cursor = collection.Find(query).SetSkip(10);
    

    The cursor is only frozen when you start iterating the cursor. That includes using it in a foreach, expanding results in the debugger and so forth. Here's an example that should fail:

    // ...
    var cursor = collection.Find(query);
    var first = cursor.FirstOrDefault();
    cursor.SetSkip(10)