The request returns MongoCursor<BsonDocument>
, which does not implement IDisposable
, so you cannot use it in the used block.
The important point is that the cursor of the enumerator should be located, and not the cursor itself, so if you used the IEnumerator<BsonDocument>
cursor directly to IEnumerator<BsonDocument>
over the cursor, then you will need to dispose of it, like this:
using (var iterator = images.Find(query).SetLimit(1).GetEnumerator()) { while (iterator.MoveNext()) { var bsonDoc = iterator.Current;
However, you'll probably never do this, and use the foreach loop instead. When an enumerator implements IDisposable, as it does, a loop using foreach ensures its Dispose()
method will be called no matter how the loop ends.
Therefore, such a cycle without explicit order is safe:
foreach (var bsonDocs in images.Find(query).SetLimit(1)) {
How to evaluate a request with Enumerable.ToList <T> , which uses a foreach loop behind the scenes:
var list = images.Find(query).SetLimit(1).ToList();
Chris fulstow
source share