Search code examples
c#mongodbmongodb-.net-driver

MongoDB. Index was out of range


I keep having this error as I try to retrieve thousands of documents from the collection.

index was out of range. must be non-negative and less than the size of the collection. parameter : Index

Here is my code as I query the documents:

        MongoCollection<Book> collection = PDatabase.GetCollection<Book>("books");
        List<IProduct> products = new List<IProduct>();
        var books = collection.Find(Query.GT("stock", 0)).SetFlags(QueryFlags.NoCursorTimeout);
        foreach (var book in books)
        {
            try
            {
                products.Add(book);
            }
            catch (Exception ex) { Console.WriteLine(ex.Message);  }
        }
        return products;

As I looked at the exception message, it says "index was out of range. must be non-negative and less than the size of the collection. Parameter : Index"


Solution

  • You mention in the comments that the underlying issue is an OutOfMemoryException.

    Answer here suggests paging best practices MongoDB - paging