這是我想在我的 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 閱讀器期待一個值,但找到了“主題”。
這里是我的 C# 類結構供參考:
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# 代碼中做錯了什么?
uj5u.com熱心網友回復:
我認為$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 } })
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/453619.html
標籤:C# mongodb 聚合框架 mongodb-.net-驱动程序
上一篇:如何將多個欄位查詢為一個
