将ListBox插入集合

时间:2016-09-19 13:17:14

标签: c# mongodb listbox

我有一个带有多个所选项目的ListBox,我尝试将一个集合插入MongoDB

守则

private async void button1_Click(object sender, EventArgs e)
    {
        // add user into datagridview from MongoDB Colelction Watchtbl
        var client = new MongoClient("mongodb://servername:27017");
        var database = client.GetDatabase("WatchTblDB");
        var collectionWatchtbl = database.GetCollection<BsonDocument>("Watchtbl");

        var document = new BsonDocument {
            { "userId", UsersComboBox.SelectedItem.ToString() },
            { "wid", WIDTxt.Text.ToString() },
            { "name", NameComboBox.SelectedItem.ToString() },
            { "Symboles" , new BsonDocument
                {
                    foreach(var item in SymbolesListBox.SelectedItems)
                    { "Name", item.ToString() }
                },
            }
        };

        await collectionWatchtbl.InsertOneAsync(document);
    }
  

集合

     
    

Watchtbl:id,userId,wid,name,Symboles

  

这是查找集合的示例

  

{“_ id”:ObjectId(“57cd794b287173b3468f6a34”),“userId”:   “57cae1c3613fb185524da68f”,“wid”:“1350”,“name”:“购买股票”,   “Symboles”:[{“Name”:“AAA”},{“Name”:“BSI”}}}   {“_ id”:ObjectId(“57cd79ab287173b3468f6a35”),“userId”:   “57cae1c4613fb185524da691”,“wid”:“1350”,“name”:“买股票”,   “Symboles”:[{“Name”:“AAA”}]}   {“_ id”:ObjectId(“57cd79b0287173b3468f6a36”),“userId”:   “57caf97b5ced6916b8970f5d”,“wid”:“1350”,“name”:“买股票”,   “Symboles”:[{“Name”:“EXXI”},{“Name”:“BSI”},{“Name”:   “AMD”}]}

enter image description here

Solution

var document = new BsonDocument();
        var arr = new BsonArray();
        document.Add("userId", UsersComboBox.SelectedItem.ToString());
        document.Add("wid", WIDTxt.Text.ToString());
        document.Add("name", NameComboBox.SelectedItem.ToString());
        foreach (var item in SymbolesListBox.SelectedItems)
        {
            arr.Add(new BsonDocument("Name", item.ToString()));
        }
        document.Add("Symboles", arr);

        await collectionWatchtbl.InsertOneAsync(document);

0 个答案:

没有答案