查找Id并将BsonArray插入集合MongoDB

时间:2016-09-22 17:49:02

标签: c# mongodb winforms

我有这个集合

    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" } ] 
        }
    ]
} )

我的表单正在从MongoDB加载Id列表,然后我选择我想要将新WatchTbl与数据一起插入的ID。 我试着找到一个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看起来我的代码无效,那么对此有什么帮助吗?

更新 添加 ntohl 的代码后 当我尝试插入集合时,我遇到了这个问题 enter image description here

1 个答案:

答案 0 :(得分:1)

我在这里有一点优势,因为我已回答你以前的帖子,我可以用它作为基础。我也添加了集合初始化部分,因为元素的类型很重要。例如,您需要在SymboleCls中设置SymbolesListBox.ItemsSource才能使其正常运行。 UsersComboBox必须有ObjectId个。您不必创建整个数组,或者如果使用Update.Set,则需要使用以前的元素填充它。相反,我使用了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));
}

用于反序列化的POCO类&gt;

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; }
}