Updating the object and object of the MongoDB array

I have an entity class stored in MongoDB that looks something like this:

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 solve the following issues:

  • Update a comment on a topic, for example: theme1.CommetList[10].Creator = "Jack"
  • How to create a page for an array object

Thanks.

Wentel


@ Andrew Orshich

Thank you for your help.

And there is one more problem:

 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?

+4
source share
2 answers

1.Using positioning 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 update the corresponding request comment as follows:

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

2. You can download the whole topic and swap comments from C # using linq, for example. Or you can also use $ slice as follows:

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

For your second question, you need to do the following:

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

All Articles