2014-10-17 103 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