Juste3alfaz
Juste3alfaz

Reputation: 295

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. And I try to find an Id then I insert into Watchtbl their Data.

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 enter image description here

Upvotes: 1

Views: 1322

Answers (1)

ntohl
ntohl

Reputation: 2125

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. And UsersComboBox must have ObjectIds. You don't have to create the whole array, or You need to fill it with previous elements, if You use Update.Set. Instead I used 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>

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

Upvotes: 1

Related Questions