Juste3alfaz Juste3alfaz - 11 months ago 63
C# Question

Insert collection into List from MongoDB

I try to get all data from collection into MongoDB server using C# driver.
The idea is connect to the server and get all collection than insert into list of class.

List<WatchTblCls> wts;
List<UserCls> users;
List<SymboleCls> syms;
public WatchTbl()
wts = new List<WatchTblCls>();
users = new List<UserCls>();
syms = new List<SymboleCls>();
public async void getAllData()
client = new MongoClient("mongodb://servername:27017");
database = client.GetDatabase("WatchTblDB");
collectionWatchtbl = database.GetCollection<WatchTbl>("Watchtbl");
collectionUser = database.GetCollection<UserCls>("Users");
collectionSymbole = database.GetCollection<SymboleCls>("Users");
var filter = new BsonDocument();

using (var cursor = await collectionWatchtbl.FindAsync(filter))
while (await cursor.MoveNextAsync())
var batch = cursor.Current;
foreach (var document in batch)
wts.Add(new WatchTblCls(document["_id"], document["userId"], document["wid"], document["name"], document["Symboles"]));

I get this error under

wts.Add(new WatchTblCls(document["_id"], document["userId"], document["wid"], document["name"], document["Symboles"]));

Cannot apply indexing with [] to an expression of type 'WatchTbl'

Answer Source

I don't understand the reason behind using WatchTbl and WatchTblCls both together. Is WatchTblCls a model for the entity WatchTbl here? Im not sure.

In any case. If you go for aggregation and want to convert WatchTbl collection to WatchTblCls list, your desired solution might look like the following. I don't know the defiitions of the classes so I'm assuming:

    var client = new MongoClient("mongodb://servername:27017");
    var database = client.GetDatabase("WatchTblDB");
    var collectionWatchtbl = database.GetCollection<WatchTbl>("Watchtbl");
    var collectionUser = database.GetCollection<UserCls>("Users");
    var collectionSymbole = database.GetCollection<SymboleCls>("Users");

    var list = collectionWatchtbl.AsQueryable().Select(x => new WatchTblCls() {
        id = x.id,
        userId = x.userId,

If you can use the same WatchTbl class and still want to load the full collection to a local List (which is definitely not a good idea):

    List<WatchTbl> list = await collectionWatchtbl.Find(x => true).ToListAsync();