Home > Back-end >  How to push an embedded array into an existing Mongodb document?
How to push an embedded array into an existing Mongodb document?

Time:03-17

Model:

    [BsonIgnoreExtraElements]
    public class UserPortfolioList
  {
    public string? Username { get; set; }
    public List<Pflist>? Pflist { get; set; }

    }

    public class Pflist
    {
        public string PfName { get; set; } = "DEFAULT NAME";
        public List<string>? Symbols { get; set; }

    }

The existing Mongodb Document:

 {
      "username": "aaa",
      "pflist": [
        {
          "pfName": "US TECH A",
          "symbols": [
            "GOOG",
            "MSFT"
          ]
        }
      ]
    }

the Array I want to push (Same username, but different pfName and symbols)

   {
      "username": "aaa",
      "pflist": [
        {
          "pfName": "US TECH C",
          "symbols": [
            "AAPL",
            "TSLA"
          ]
        }
      ]
    }

the expected result is

       {
          "username": "aaa",
          "pflist": [
                 {
                  "pfName": "US TECH A",
                  "symbols": [
                    "GOOG",
                    "MSFT"
                  ]
                },
                {
                 "pfName": "US TECH C",
                 "symbols": [
                   "AAPL",
                   "TSLA"
                  ]
                }
            ]
          }

the Code I have:

public async Task UpdateUserPfAsync(UserPortfolioList userPflist)

await _UserPortfoliosCollection.UpdateOneAsync(Builders<UserPortfolioList>.Filter.Eq(
    "Username", userPflist.Username),
    Builders<UserPortfolioList>.Update.Push(x => x.Pflist, userPflist.Pflist));

The complier thrown out a error : can not convert lambda express to type......

I almost tried every approaching on the stackoverflow, but none of them works for me.

Please help. Thank you!

CodePudding user response:

Concern:

Since you are adding a single object to pflist, you should use userPflist.Pflist[0] instead of userPflist.Pflist as with userPflist.Pflist will lead to the result:

{
  username: "aaa",
  pflist: [
    0: Object
    1: Array
      0: Object
  ]
}

Push single element to the array

MongoDB query:

db.collection.update({
  username: "aaa"
},
{
  $push: {
    "pflist": {
      "pfName": "US TECH C",
      "symbols": [
        "AAPL",
        "TSLA"
      ]
    }
  }
})

enter image description here

  • Related