我怎样才能展平这个子文档数组?

How can I flatten this array of subdocuments?

这是我要在我的 C# 代码中执行的查询:

db.Courses.aggregate([
  {$unwind: "$topics"},
  {$project: {"topics":1, _id:0}},
  {$replaceRoot:{newRoot:"$topics"}}
])

当我在 MongoDB shell:

中执行它时,这给了我这个输出
{ _id: null,
  title: 'My Topic',
  description: 'My Topic Desc',
  lessons: 
   [ { lessonId: 'Lessonid1',
       title: 'My Lesson',
       description: 'My Lesson Desc' } ] }

这正是我想要的。我将其翻译成 C# 的尝试是:

var topics = await collection.Aggregate()
    .Unwind<Course>(c=>c.Topics)
    .Project("topics")
    .ReplaceRoot<Topic>(newRoot:"$topics")
    .ToListAsync();

不幸的是,这不起作用,我得到了这个错误:

System.FormatException: JSON reader was expecting a value but found 'topics'.

参考这里是我的 C# class 结构:

public class Course
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string? CourseId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public List<Topic>? Topics { get; set; }
}

public class Topic
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string? TopicId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }

    public List<LessonSummary>? Lessons { get; set; }

}

public class LessonSummary
{
    public string LessonId { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}

这是我正在使用的集合中的完整数据:

[
  {
    "courseId": "624487662a2b383f7306c5ad",
    "title": "My Course",
    "description": "My Course Desc",
    "topics": [
      {
        "topicId": null,
        "title": "My Topic",
        "description": "My Topic Desc",
        "lessons": [
          {
            "lessonId": "Lessonid1",
            "title": "My Lesson",
            "description": "My Lesson Desc"
          }
        ]
      }
    ]
  }
]

我在与 MongoDB shell 不同的 C# 代码中做错了什么?

我认为$project阶段可以从你的场景中跳过。

db.Courses.aggregate([
  {$unwind: "$topics"},
  {$replaceRoot:{newRoot:"$topics"}}
])
var topics = await collection.Aggregate()
    .Unwind<Course>(c=>c.Topics)
    .ReplaceRoot<Topic>(newRoot:"$topics")
    .ToListAsync();

如果你需要$project阶段,你可以通过BsonDocument作为

.Project("{ topics: 1, _id: 0 }")

.Project(new BsonDocument { { "topics", 1 }, { "_id", 0 } })