使用子文档数组按排序顺序查询mongodb集合

时间:2015-01-01 10:34:30

标签: 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; } 
}

Public Class QuizModel
{
 [BsonId]
 [BsonRepresentation(BsonType.ObjectId)]
 public string Id { get; set; }

 public string QuizName {get; set;}
}

当我保存时,它会在db中生成如下结构:

{
    "_id" : ObjectId("54a4e902bb63bc1370aff4a7"),
    "WSName" : "WS2",
    "UserId" : "54a4e902bb63bc1370aff5b9",
    "Quiz" : [
     {
      "_id" : null,
      "QuizName " : "Qz2"
     },
     {
      "_id" : null,
      "QuizName " : "Qz1"
     },
     {
      "_id" : null,
      "QuizName " : "Qz2"
     },
    ]
},

我使用以下查询来获取按“WSName”

排序的工作表列表
_collection = _db.GetCollection<WorksheetModel>("Worksheets");
_query = Query<WorksheetModel>.Where( e => e.UserId == oModel.UserId);
_cursor = _collection.Find(_query).SetSortOrder(SortBy.Ascending("WSName"));

但是现在我想以这样的方式检索工作表列表,其中子文档数组测验也应该由QuizName 排序。

最终结果应如下所示:

{
        "_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"
         },
        ]
    },

现在我应该如何从C#查询文档,以便获得结果。

0 个答案:

没有答案