简体   繁体   中英

How to convert List<BsonDocument> to List<Class> in C#

Here what I am trying to do is to convert List of Bson Document to the list of Class. The main purpose of doing so is to filter the data from the list of Json data. I am using MongoDb for my database and C# for handling data. I have stored some data in MongoDb and trying to filter the data using FilterDefinition like this:

PROCESS 1

 FileContext context = new FileContext();
 var collection = context.Db.GetCollection<BsonDocument>("DBCollection");
 var builder = Builders<BsonDocument>.Filter;
 FilterDefinition<BsonDocument> Filter = builder.Eq("FileName", fileDetail.FileName) & builder.Eq("FileNumber", fileDetail.FileNumber.ToString());
 var list = await collection.Find(Filter).ToListAsync();

In this way I am not been able to get the data in list. Therefore, I tried the other way like this:

PROCESS 2

 FileContext context = new FileContext();
 var collection = context.Db.GetCollection<BsonDocument>("DBCollection");
 var list = await collection.Find(_ => true).ToListAsync();
 List<MyClass> objList = null;
 foreach (var item in objList)
 {
   objList = new List<MyClass>();
   objList.Add(BsonSerializer.Deserialize<MyClass>(item));
 }
 if(objList.Count >0)
 {
    int count = objList.Where(x => x.FileName == "SOME_FILE_NAME" && x.FileNumber == 1).Count();
 }

This way I am able to get the data and able to filter data as well but I know this is not good programming at all as this will have lots of waiting time if the size of data increases in future.

Here my questions are:

  1. What is wrong in PROCESS 1 ?
  2. How to Convert List<BsonDocument> to List<MyClass> ?
  3. How to filter List<BsonDocument> ?
var collection = context.Db.GetCollection<BsonDocument>("DBCollection");

should be:

var collection = context.Db.GetCollection<MyClass>("DBCollection");

That way you should be able to use the Find method to check your FileName and FileNumber using something like:

var objList = await collection.Find(x => x.FileName == "FILENAMEHERE" && x.FileNumber == 1).ToListAsync();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM