使用FindAndModify更新特定集合项的属性

时间:2014-10-17 21:23:05

标签: mongodb mongodb-query mongodb-.net-driver

发布课程:

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

评论类:

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

如果DeletionDateComment等于给定参数,我希望在Post.Comments内设置Comment.Id的{​​{1}}属性。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

QueryDocument query= new QueryDocument();
            query.Add(new BsonDocument("Comments.$.Id","givenCommentId"));
            UpdateDocument update = new UpdateDocument();
            update.Add(new BsonElement("Comments.$.DeletionDate", "yourUpdatedDate"));

您可以在FindAndModifyArgs

中使用它

但是我忘记了位置运算符$是否可用于两个或多个字段,因此我不在查询中添加new BsonDocument("Comments.$.CreatorId","givenCommentCreatorId")。您需要对其进行测试。

答案 1 :(得分:0)

我解决了以下问题:

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