title: Deserialize mongodb Bson file into List of objects
body: <p>this answer answers my question: <a href="https://stackoverflow.com/a/71792264/637142">https://stackoverflow.com/a/71792264/637142</a></p>
  <p>The problem with that answer is that it is very ineficient. It takes 7 seconds to deserialize 1 million objects on my computer. If I where to get all those million objects directly from the database it will take only 0.5 seconds.</p>
  <p>Anyways here is the code I have so far:</p>
  <p>Dump all 1 million animals to disk. Takes less than 1 second.</p>
  <pre><code>// dump all Animals using mongodump command
  mongodump --db=MyDb --collection=Animals --out=/tmp/output
  </code></pre>
  <p>Read all 1 million animals from c#. Takes less than 1 second</p>
  <pre><code>var dbName = &quot;MyDb&quot;;
  var mongoClient = new MongoClient(&quot;mongodb://localhost:27017&quot;);
  var mongoDb = mongoClient.GetDatabase(dbName);
  var collection = mongoDb.GetCollection&lt;Animal&gt;(&quot;Animals&quot;);
  var records = collection.Find(&quot;{}&quot;).ToList();
  </code></pre>
  <p>Read all 1 million animals from bson file /tmp/output/MyDb/Animals.bson file. Takes more than 7 seconds:</p>
  <pre><code>var path = &quot;/tmp/output/MyDb/Animals.bson&quot;;
  await using var bsonFileStream = File.OpenRead(path);
  var fileSize = new FileInfo(path).Length;
  
  
  var binaryReader = new BsonBinaryReader(bsonFileStream);
  var serializer = BsonSerializer.LookupSerializer&lt;Animal&gt;();
  var bsonDeserializationContext = BsonDeserializationContext.CreateRoot(binaryReader, null);
  
  var args1 = new BsonDeserializationArgs()
  {
      NominalType = serializer.ValueType
  };
  
  
  // keep reading until we reach end of file
  while (bsonFileStream.Position&lt;fileSize)
  {
      Animal output =  serializer.Deserialize(bsonDeserializationContext, args1);        
  }
  </code></pre>
  <p>Is there a way I can use the serializer to deserialize a listof animal instead of having to deserialize one by one?</p>