I have a question regarding C# using MongoDB. Here is a simplified version of my program.
I have one customer Class named Record as follows:
public class Record
{
public ObjectId _id { get; set;}
public int[] a { get; set;}
public int[] b { get; set;}
public int[] c { get; set;}
public int[] d { get; set;}
public int[] e { get; set;}
public int[] f { get; set;}
}
It works perfectly as long as I operate everything using this class as customer datatype, e.g.
var collection = database.GetCollection<Record>("mycollection");
List<Record> list = collection.Find("{}").ToList();
However, some of my feature just need a projection instead of a whole document, and I prefer to use a projection when querying data due to the rapid data growth rate, and my code is like:
var projection = Builders<Record>.Projection.Include("a");
var list collection.Find(filter).Project(projection).ToList();
Now, I can't convert the list
as a list of Record
, but a list of BsonDocument
because I made a projection, and consequently, when I perform operation on each item
in the list
, the item
is recognized as BsonDocument
, thus the variable a
is considered as a BsonValue
instead of an int[]
. It seems Mongodb only provided a method asBsonArray
to cast a
into an array of BsonValue
, but I can't conviniently convert the values inside the array into int
.
I can cast the values one by one, but this is super time-consuming. I also thought about creating some classes with only fields needed and try to convert the query results into those classes, but I'm not sure if this would work, and even it works, this means I need a new class every time when I use a different projection.
Is there anything I can do to use projection but keep the data type information of Record
at the same time?
All you need to do is to specify the expected return type of the projetion when calling Project
:
var projection = Builders<Record>.Projection.Include("a");
var list = collection.Find(filter).Project<Record>(projection).ToList();
Then, you have a ´List´ as the result with only the Id
and a
properties filled. The other arrays are null
.