2016-10-23 9 views
0

はここ取得MongoDBのサブドキュメント

{ 
"_id" : ObjectId("580bc94b221036257caf2636"), 
"Status" : "Scheduled", 
//I want to get this Questions list 
"Questions" : [ 
    { 
     "QuestionType" : "Choice", 
     "Question" : "What is your name?", 
     "Correct" : "C", 
     "Options" : [ 
      "xxx", 
      "xxx", 
      "xxx" 
     ] 
    }, 
{ 
     "QuestionType" : "Choice", 
     "Question" : "What is your name?", 
     "Correct" : "C", 
     "Options" : [ 
      "xxx", 
      "xxx", 
      "xxx" 
     ] 
    } 
] 

}

は私のクエリ

var collection = mongodb.GetCollection<QuestionsList>("Papers"); 
     var choice = collection.Find(Query.EQ("userName", "Sohail")).SetFields(Fields.Exclude("status") 
      .Slice("Questions", 1)).Single(); 
     return choice.multiQuestions.ToList(); 

である私は、過去1週間のためにこれをしようとしていますが、何も 私が働いているようだ、次のデータを検討します質問はどのようにしてこの質問リストを取得してMVCビューに表示できるのですか? おかげで

答えて

0

まず、あなたがあなたが上方に設けられているデータ構造に基づいているように思われないドキュメントのユーザー名フィールド照会されて表示されます。

.Find(Query.EQ("userName", "Sohail")) 

をしかし、これはタイプミスだったと仮定すると... 。

あなたが質問の組み込み配列を返すために、ここで$プロジェクトを使用することができます。

var collection = mongodb.GetCollection<QuestionsList>("Papers"); 

var projection = Builders<QuestionsList>.Projection.Include("Questions"); 
var choice = collection 
       .Find(Query.EQ("userName", "Sohail")) 
       .Project(projection) 
       .ToList(); 

return choice; 

あなたがC#のモデルを持っているように見えます(QuestionsList)強く型付けされたクエリを使用していない理由は何ですか?あなたのモデルを仮定すると、次のようになります

public class QuestionsList 
{ 
    [BsonRepresentation(BsonType.ObjectId)] 
    [BsonId] 
    public string Id { get; set; } 

    //Missing from your data structure but assume it is there 
    public string userName { get; set; } 

    public string Status { get; set; } 

    public List<Question> Questions { get; set; } 
} 

public class Question 
{ 
    public string QuestionType { get; set; } 
    public string Question { get; set; } 
    public string Correct { get; set; } 
    public List<string> Options { get; set; } 
} 

相当

var choice = collection 
       .Find(x => x.userName == "Sohail")) 
       .Project(x => x.Questions) 
       .ToList(); 
だろう
関連する問題