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

Mongodb 正在使用FindAndModify更新特定集合项的属性,mongodb,mongodb-query,mongodb-.net-driver,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 strin

邮班:

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.Id
Comment.CreatorId
等于给定参数,我想在
Post.Comments
中找到设置
Comment
DeletionDate
属性

我该怎么做

QueryDocument query= new QueryDocument();
            query.Add(new BsonDocument("Comments.$.Id","givenCommentId"));
            UpdateDocument update = new UpdateDocument();
            update.Add(new BsonElement("Comments.$.DeletionDate", "yourUpdatedDate"));
您可以在FindModifyArgs中使用它


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

我用以下方法解决了这个问题:

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);
var query=query.ElemMatch(p=>p.Comments,builder=>
建筑商。以及(
EQ(c=>c.Id,commentId),
EQ(c=>c.CreatorId,CreatorId));
var update=update.Set(“Comments.$.DeletionDate”,DateTime.UtcNow);
var args=new find modifyargs
{
Query=Query,
更新=更新
};
var result=_db.Posts.FindAndModify(args);

这没有按原样工作,但是感谢您提到位置运算符,这是我的更新命令中需要的。我用
“$elemMatch”
解决了这个问题。
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);