简体   繁体   English

从MongoDB将集合插入列表

[英]Insert collection into List from MongoDB

I try to get all data from collection into MongoDB server using C# driver. 我尝试使用C#驱动程序将所有数据从集合中获取到MongoDB服务器中。 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()
{
 InitializeComponent();
 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' 无法将[]的索引应用于'WatchTbl'类型的表达式

I don't understand the reason behind using WatchTbl and WatchTblCls both together. WatchTblCls同时使用WatchTblWatchTblCls的原因。 Is WatchTblCls a model for the entity WatchTbl here? WatchTblCls为实体模型WatchTbl在这里? 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. 如果您要进行汇总并希望将WatchTbl集合转换为WatchTblCls列表,则所需的解决方案可能如下所示。 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): 如果您可以使用相同的WatchTbl类,并且仍然希望将完整集合加载到本地List中(这绝对不是一个好主意):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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