开发者

MongoDB array object Update and Page

I've a entity class stored in MongoDB that looks similar to these:

public class Theme
{
    public ObjectId Id { get; set; }
    public string Description { get; set; }
    public string Title { get; set; }
    public List<Comment> CommentList { get; set; }
}


public class Comment
{
    public string Content { get; set; }
    public 开发者_高级运维string Creator { get; set; }
    public string Date { get; set; }
}

Using the MongoDB C# driver,and based on the model, how can i resolve for the following questions:

  1. Update a comment of the theme, eg: theme1.CommetList[10].Creator = "Jack"
  2. How to page for the array object

Thanks.

Wentel


@Andrew Orsich

Thanks for your help.

And there is another trouble:

var query = Query.EQ("Id", id);   //The 'id' type is ObjectId
List<Theme> newDatas = themeCollection.FindAs<Theme>(query).ToList();
Theme newData = themeCollection.FindOneByIdAs<Theme>(allDatas[0].Id);

Result: 'newDatas' is null and 'newData' has data, why?


1.Using positional operator:

var query = Query.And(Query.EQ("Id", id));
var update = Update.Set("CommetList.10.Creator", "Jack");

Also you probably need to add id to the Comment class. In this case you can updated matched by query comment like this:

var query = Query.And(Query.EQ("Id", id), Query.EQ("CommentList.Id", commentId));
var update = Update.Set("CommentList.$.Creator", "Jack");

2.You can load entire theme and do paging of comments from c# using linq for example. Or you can also use $slice like this:

var comments = themeCollection
               .FindAs<Comment>()
               .SetFields(Fields.Slice("Comments", 40, 20))
               .ToList(); 


For your second question you need to do the following:

 ObjectId oid = new ObjectId(id);
 var query = Query.EQ("_id", oid);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜