gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:00:32 25 4
gpt4 key购买 nike

我有这个 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"
}
}
]
}
]
}

我试过用这个:

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

我也试过把过滤器改成

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

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

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

最佳答案

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

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

关于c# - 使用 C# 在 MongoDB 中查询、过滤和更新多级嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35040747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com