MongoDB: delete cursor

Excerpt from C # driver:

It is important that a cursor cleanly release any resources it holds. The key to guaranteeing this is to make sure the Dispose method of the enumerator is called. The foreach statement and the LINQ extension methods all guarantee that Dispose will be called. Only if you enumerate the cursor manually are you responsible for calling Dispose.

The cursor "res" created when called:

 var res = images.Find(query).SetFields(fb).SetLimit(1); 

does not have a Dispose method. How can I get rid of it?

+7
source share
2 answers

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; // do something with bsonDoc } } 

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)) { // do something with bsonDoc } 

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(); 
+8
source

You do not need to call Dispose on the cursor (in fact, MongoCursor does not even have a Dispose method). What you need to do is call Dispose on the enumerator returned by the GetEnumerator MongoCursor method. This happens automatically when you use the foreach statement or any of the LINQ methods that iterate over IEnumerable. Therefore, if you do not call GetEnumerator yourself, you do not need to worry about choosing Dispose.

+3
source

All Articles