2014-10-17 97 views
0

Post类:更新特定集合项目的性质与FindAndModify

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

我想找个设置CommentDeletionDate财产Post.Comments内因为Comment.IdComment.CreatorId等于给定的参数。

我该怎么做?

回答

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); 
1
QueryDocument query= new QueryDocument(); 
      query.Add(new BsonDocument("Comments.$.Id","givenCommentId")); 
      UpdateDocument update = new UpdateDocument(); 
      update.Add(new BsonElement("Comments.$.DeletionDate", "yourUpdatedDate")); 

可以在FindAndModifyArgs

不过,我已经忘记了whehther位置操作$可用于两个或多个字段使用它,所以我不添加new BsonDocument("Comments.$.CreatorId","givenCommentCreatorId")在query.You需要对其进行测试。

+0

这并没有工作,因为它是,但感谢你提的位置操作,这是需要我的更新命令。我用'“$ elemMatch”'解决了它。 – 2014-10-18 16:52:28