使用 C# 查询、过滤和更新 MongoDB 中的多级嵌套数组

Cis*_*sco 4 c# mongodb mongodb-csharp-2.0

我有这个 MongoDB 文档。我正在开发一个 MVC 应用程序并尝试使用 C# 更新注释数组(注释描述为“更新后注释”)。我正在使用新的 mongodb 版本。

{
   "ProjectID":1,
   "ProjectName":"Project test",
   "ProjectStatus":"Active",
   "ProjectTasks":[
      {
         "ProjectTaskID":1,
         "TaskShortDescription":"short task description",
         "TaskLongDescription":"long task description",
         "Comments":[
            {
               "CommentID":1,
               "CommentDescription":"comment before update",
               "CreatedBy":"Mike",
               "UploadDocuments":{
                  "TaskID":null,
                  "CommentID":null,
                  "UploadDocumentID":1,
                  "UploadDocumentName":"first document upload"
               }
            }
         ]
      }
   ]
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用这个:

var filter = Builders<Project>.Filter.And(Builders<Project>.Filter.Eq(x => x.ProjectID, projectID), Builders<Project>.Filter.ElemMatch(x => x.ProjectTasks, x => x.ProjectTaskID == projectTaskID), Builders<Project>.Filter.ElemMatch(x => x.ProjectTasks.ElementAt(-1).Comments, x => x.CommentID == comment.CommentID));

var update = Builders<Project>.Update.Set(x => x.ProjectTasks.ElementAt(-1).Comments.ElementAt(-1).CommentDescription, comment.CommentDescription );

Collection.UpdateOneAsync(filter, update, new UpdateOptions() { IsUpsert = true });
Run Code Online (Sandbox Code Playgroud)

我也尝试将过滤器更改为

var filter = Builders<Project>.Filter.And(Builders<Project>.Filter.Where(p => p.ProjectID == projectID), Builders<Project>.Filter.Eq("ProjectTasks.ProjectTaskID", projectTaskID), Builders<Project>.Filter.Eq("ProjectTasks.$.Comments.$.CommentID", comment.CommentID));
Run Code Online (Sandbox Code Playgroud)

对于这两种情况,我都无法查询、过滤和更新评论。

您能告诉我如何查找和更新本文档中的评论吗?任何建议都非常感谢!

小智 5

您应该使用 $[] 多个位置运算符,我将尝试为您粘贴的代码编写您应该使用的内容:

var baseFilter = Builders<Project>.Filter.Eq("ProjectID": 1);
var update = Builders<Project>.Update.Set("ProjectTasks.$[i].Comments.$[j].CommentDescription", comment.CommentDescription);

var arrayFilters = new List<ArrayFilterDefinition>
{
    /* change the type names here if they have different names, I just guessed */
    new BsonDocumentArrayFilterDefinition<ProjectTask>(new BsonDocument("i.ProjectTaskID", projectTaskID)),
    new BsonDocumentArrayFilterDefinition<Comment>(new BsonDocument("j.CommentId", commentID))
};

var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters };

await Collection.UpdateOneAsync(baseFilter, update, updateOptions);
Run Code Online (Sandbox Code Playgroud)