C# 按排序顺序查询子文档数组的mongodb集合
我有以下模型结构:C# 按排序顺序查询子文档数组的mongodb集合,c#,mongodb,mongodb-.net-driver,C#,Mongodb,Mongodb .net Driver,我有以下模型结构: Public Class WorksheetModel { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } public string WSName {get; set;} public string UserId {get; set;} public List<QuizModel> Quiz { get; set; } } Pub
Public Class WorksheetModel
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string WSName {get; set;}
public string UserId {get; set;}
public List<QuizModel> Quiz { get; set; }
}
Public Class QuizModel
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string QuizName {get; set;}
}
我使用以下查询获取按WSName排序的工作表列表
_collection = _db.GetCollection<WorksheetModel>("Worksheets");
_query = Query<WorksheetModel>.Where( e => e.UserId == oModel.UserId);
_cursor = _collection.Find(_query).SetSortOrder(SortBy.Ascending("WSName"));
现在,我应该如何从C查询文档,以便得到上面的结果。在检索时,您始终可以在根级别对文档进行排序。但在进行查找时,不能对数组元素进行排序,原因很简单,因为这样就变成了对文档数据的操作。要操纵数组元素的顺序,即对它们进行排序,您可以遵循两种方法—执行聚合操作或在插入和更新期间按排序顺序存储数组元素。一个这样的用例已经在这里讨论过了,虽然不是在c中,这可能会有所帮助。-。您可以为WorksheetModel编写自定义序列化程序,当它对文档进行反序列化时,您可以在反序列化方法中对嵌入数组进行排序
_collection = _db.GetCollection<WorksheetModel>("Worksheets");
_query = Query<WorksheetModel>.Where( e => e.UserId == oModel.UserId);
_cursor = _collection.Find(_query).SetSortOrder(SortBy.Ascending("WSName"));
{
"_id" : ObjectId("54a4e902bb63bc1370aff4a7"),
"WSName" : "WS1",
"UserId" : "54a4e902bb63bc1370aff5b9",
"Quiz" : [
{
"_id" : null,
"QuizName " : "Qz1"
},
{
"_id" : null,
"QuizName " : "Qz2"
},
{
"_id" : null,
"QuizName " : "Qz2"
},
]
},
{
"_id" : ObjectId("54a4e902bb63bc1370aff4a7"),
"WSName" : "WS2",
"UserId" : "54a4e902bb63bc1370aff5b9",
"Quiz" : [
{
"_id" : null,
"QuizName " : "Qz4"
},
{
"_id" : null,
"QuizName " : "Qz4"
},
{
"_id" : null,
"QuizName " : "Qz5"
},
]
},