简体   繁体   中英

Append element to array on existing item with MongoDB & C#

I need to append a new comment to a array element that is part of a MongoDB document via C# but can't figure out how to do it.

The strange thing is that when I'm inserting a document with tags which are stored in an array of string element, it works as expected:

var post = new Post
{
    Title = model.Title,
    Author = User.Identity.Name,
    CreatedAtUtc = DateTime.Now,
    Content = model.Content,
    Tags = model.Tags.Split(",".ToCharArray()).ToList()
};

Now when I try to add a new comment to an existing document, I use the following:

var filter = Builders<Post>.Filter.Eq("_id", model.PostId);

var update = Builders<Post>.Update.Push<Comment>("Comments", 
    new Comment
    {
        Author = User.Identity.Name,
        CreatedAtUtc = DateTime.Now,
        Content = model.Content
    });

var ret = await blogContext.Posts.FindOneAndUpdateAsync(filter, update);

But this leaves my Comments element empty in my document:

"_id" : ObjectId("5b82ec466b63730fe4c51915"),
"Author" : "Joe",
"Content" : "content1",
"CreatedAtUtc" : ISODate("2018-08-26T18:06:53.238Z"),
"Title" : "title1",
"Comments" : [ ],
"Tags" : [
    "tag1.1",
    "tag1.2",
    " tag2.2"
]

Can anyone clarify how do I append an additional comment to an existing document?

Thanks

UPDATE-1:

I've found this question on StackOverflow: How to use $push update modifier in MongoDB and C#, when updating an array in a document which described my exact problem, except that the array used in an array of string rather than an array of object/document but I still thought it would resolved it by adapting my code to match it:

var filter = Builders<Post>.Filter.Eq("_id", model.PostId);
var update = Builders<Post>.Update
    .Push<Comment>(e => e.Comments, new Comment
        {
            Author = User.Identity.Name,
            CreatedAtUtc = DateTime.Now,
            Content = model.Content
        });

await blogContext.Posts.FindOneAndUpdateAsync(filter, update);

but this is still leaving my Comments array element empty just as posted in the original question.

Any ideas?

The code provided in Update-1 of my question is correct and the problem was all along related to another issue!

The Model.PostId needed to be converted to an ObjectId:

var filter = Builders<Post>.Filter.Eq("_id", new ObjectId(model.PostId));

Once converted, the "comment" got appended as expected to the "Comments" array property of the document.

Really frustrating that it does not throw an error to let you know that the type used is invalid! Wasted a huge amount of time on a silly mistake but lesson learned I guess!!

Hope this helps others!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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