简体   繁体   English

查找 Id 并将 BsonArray 插入到集合 MongoDB 中

[英]Find Id and insert a BsonArray into collection MongoDB

I have this collection我有这个收藏

    db.UserWatchtbl.insert( { 
fbId: "", 
Name: "user3", 
pass: "pass3",
Watchtbl: 
    [ 
        { 
        wid: "1350",
        name: "bought stock1",
        Symboles: [ { Name: "AAA" }, { Name: "BSI" } ] 
        },
        { 
        wid: "1350",
        name: "bought stock2",
        Symboles: [ { Name: "AAA" }, { Name: "BSI" }, { Name: "EXXI" } ] 
        },
        { 
        wid: "1350",
        name: "bought stock2",
        Symboles: [ { Name: "AAA" }, { Name: "BSI" }, { Name: "EXXI" } ] 
        }
    ]
} )

My form is loading the Id list from the MongoDB then I select the ID that I want to insert the new WatchTbl with the data.我的表单正在从 MongoDB 加载 Id 列表,然后我选择要插入带有数据的新 WatchTbl 的 ID。 And I try to find an Id then I insert into Watchtbl their Data.我尝试找到一个 ID,然后将他们的数据插入到Watchtbl 中

private async void button1_Click(object sender, EventArgs e)
    {
        // add user into datagridview from MongoDB Colelction Watchtbl
        var client = new MongoClient("mongodb://dataservername:27017");

        var database = client.GetDatabase("WatchTblDB");
        var collectionWatchtbl = database.GetCollection<BsonDocument>("UserWatchtbl");

        var document = new BsonDocument();
        BsonArray arrSym = new BsonArray();
        BsonArray arrWatc = new BsonArray();

        document.Add("wid", WIDTextBox.Text.ToString());
        document.Add("name", NameComboBox.SelectedItem.ToString());

        foreach (var item in SymbolesListBox.SelectedItems)
        {
            arrSym.Add(new BsonDocument("Name", item.ToString()));
        }
        document.Add("Symboles", arrSym);

        arrWatc.Add(new BsonDocument("Watchtbl", document));



        var result = await collectionWatchtbl.FindOneAndUpdateAsync(
                            Builders<BsonDocument>.Filter.Eq("_id", UsersComboBox.SelectedItem.ToString()),
                            Builders<BsonDocument>.Update.Set("Watchtbl", arrWatc)
                            );
    }

Bu It looks my code not working, So any help with that?但是看起来我的代码不起作用,所以有什么帮助吗?

Update After Add the code of ntohl I face this problem when I try to insert into collection添加ntohl代码后更新我在尝试插入集合时遇到此问题在此处输入图片说明

I have a little advantage here, because I have answered Your previous post, and I could use it as a base.我在这里有一点优势,因为我已经回答了您之前的帖子,我可以将其用作基础。 I have added the collection initialization part also, because the type of the elements are important.我还添加了集合初始化部分,因为元素的类型很重要。 You need to have SymboleCls in the SymbolesListBox.ItemsSource to have it work for example.例如,您需要在SymbolesListBox.ItemsSourceSymboleCls才能使其工作。 And UsersComboBox must have ObjectId s.并且 UsersComboBox 必须有ObjectId s。 You don't have to create the whole array, or You need to fill it with previous elements, if You use Update.Set .如果您使用Update.Set ,则不必创建整个数组,或者您需要用以前的元素填充它。 Instead I used AddToSet .相反,我使用了AddToSet

private readonly IMongoCollection<BsonDocument> collectionWatchtbl;

public MainWindow()
{
    InitializeComponent();
    var client = new MongoClient("mongodb://localhost:27017");

    var database = client.GetDatabase("test");
    collectionWatchtbl = database.GetCollection<BsonDocument>("UserWatchtbl");

    var filter = new BsonDocument();
    var user = new List<UserWatchTblCls>();
    var cursor = collectionWatchtbl.FindAsync(filter).Result;
    cursor.ForEachAsync(batch =>
    {
        user.Add(BsonSerializer.Deserialize<UserWatchTblCls>(batch));
    });

    UsersComboBox.ItemsSource = user.Select(x => x.Id);
    SymbolesListBox.DisplayMember = "Name";
    SymbolesListBox.ItemsSource =
        user.SelectMany(x => x.WatchTbls).SelectMany(y => y.Symbols);
}

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    var document = new BsonDocument();
    BsonArray arrSym = new BsonArray();
    //BsonArray arrWatc = new BsonArray();

    document.Add("wid", WIDTextBox.Text.ToString());
    document.Add("name", NameComboBox.SelectedItem.ToString());

    foreach (SymboleCls item in SymbolesListBox.SelectedItems)
    {
        arrSym.Add(new BsonDocument("Name", item.Name));
    }
    document.Add("Symboles", arrSym);

    // needed only when replacing the Watchtbl
    //arrWatc.Add(document);

    // Do You really need to use async?
    collectionWatchtbl.UpdateOne(Builders<BsonDocument>.Filter.Eq("_id", UsersComboBox.SelectedItem), Builders<BsonDocument>.Update.AddToSet("Watchtbl", document));
}

And the POCO classes for deserialize>以及用于反序列化的 POCO 类>

public class UserWatchTblCls
{
    [BsonId]
    [BsonElement("_id")]
    public ObjectId Id { get; set; }

    public string fbId { get; set; }
    public string Name { get; set; }

    [BsonElement("pass")]
    public string Pass { get; set; }

    [BsonElement("Watchtbl")]
    public List<WatchTblCls> WatchTbls { get; set; }
}

public class WatchTblCls
{
    [BsonElement("wid")]
    public string WID { get; set; }

    [BsonElement("name")]
    public string Name { get; set; }

    [BsonElement("Symboles")]
    public List<SymboleCls> Symbols { get; set; }
}

public class SymboleCls
{
    public string Name { get; set; }
}

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

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