Search code examples
mongodbmongodb-querymongodb-.net-driver

Updating property of specific collection item with FindAndModify


Post class:

public class Post
{
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; } 
    [BsonRepresentation(BsonType.ObjectId)]
    public string CreatorId { get; set; }
    public string CreatorName { get; set; }
    public string Text { get; set; }
    public bool IsPublic { get; set; }
    public ICollection<Comment> Comments { get; set; }
    public DateTime CreationDate { get { return ObjectId.Parse(Id).CreationTime; } }
    public DateTime? DeletionDate { get; set; }
}

Comment class:

public class Comment
{
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    [BsonRepresentation(BsonType.ObjectId)]
    public string CreatorId { get; set; }
    public string CreatorName { get; set; }
    public string Text { get; set; }
    public DateTime CreationDate { get { return ObjectId.Parse(Id).CreationTime; } }
    public DateTime? DeletionDate { get; set; }
}

I would like to find set the DeletionDate property of a Comment inside a Post.Comments given that Comment.Id and Comment.CreatorId equals the given parameters.

How can I do this?


Solution

  • I solved it with the following:

    var query = Query<Post>.ElemMatch(p => p.Comments, builder => 
        builder.And(
            Query<Comment>.EQ(c => c.Id, commentId),
            Query<Comment>.EQ(c => c.CreatorId, creatorId)));
    
    var update = Update.Set("Comments.$.DeletionDate", DateTime.UtcNow);
    
    var args = new FindAndModifyArgs
    {
        Query = query,
        Update = update
    };
    
    var result = _db.Posts.FindAndModify(args);