2011-05-10 29 views
0

我正在將單個文檔讀入BsonDocument對象。從MongoDB讀取文檔後,我想查詢內存中的文檔。 我的文檔看起來是這樣的:MongoDB - 內存中的查詢BsonDocument

{ 
    "_id": { 
    "$binary": "DYibd4bSz0SFXTTmY46gOQ==", 
    "$type": "03" 
    }, 
    "title": "XYZ 2011", 
    "pages": [ 
    { 
     "pagetype": "contactcapture", 
     "pagetitle": "Contact", 
     "questions": [ 
     { 
      "qtype": "text", 
      "text": "Firstname", 
      "name": "firstname" 
     }, 
     { 
      "qtype": "text", 
      "text": "Surname", 
      "name": "surname" 
     }, 
     { 
      "qtype": "text", 
      "text": "Company", 
      "name": "companyname" 
     } 
     ] 
    }, 
    { 
     "pagetype": "question", 
     "pagetitle": "Question 1", 
     "questions": [ 
     { 
      "qtype": "radio", 
      "text": "What drink?", 
      "name": "drink", 
      "answers": [ 
      { 
       "text": "Tea" 
      }, 
      { 
       "text": "Coffee" 
      }, 
      { 
       "text": "Hot chocolate" 
      }, 
      { 
       "text": "Water" 
      } 
      ] 
     } 
     ] 
    }, 
    { 
     "pagetype": "question", 
     "pagetitle": "Question 2", 
     "questions": [ 
     { 
      "qtype": "check", 
      "text": "Accompaniments?", 
      "name": "accompaniments", 
      "answers": [ 
      { 
       "text": "Nuts" 
      }, 
      { 
       "text": "Crisps" 
      }, 
      { 
       "text": "Biscuits" 
      } 
      ] 
     } 
     ] 
    }, 
    { 
     "pagetype": "question", 
     "pagetitle": "Question 3", 
     "questions": [ 
     { 
      "qtype": "radio", 
      "text": "When would you like that?", 
      "name": "when", 
      "answers": [ 
      { 
       "text": "Immediately" 
      }, 
      { 
       "text": "10 minutes" 
      }, 
      { 
       "text": "Half-an-hour" 
      } 
      ] 
     }, 
     { 
      "qtype": "text", 
      "text": "Anything else with that?", 
      "name": "anythingelse" 
     } 
     ] 
    } 
    ] 
} 

我希望得到的是有一個網頁類型=「問題」的所有頁面。我目前做如下:

BsonDocument profileDocument= profilesCollection.FindOneByIdAs<MongoDB.Bson.BsonDocument>(binaryId); 
BsonElement pagesElement = profileDocument.GetElement("pages"); 
BsonArray pages=profileDocument.GetElement("pages").Value.AsBsonArray; 
foreach (BsonValue pageV in pages.Values) 
{ 
    BsonDocument page = pageV.AsBsonDocument; 
    if (page["pagetype"].AsString == "question") 
    { 
     sb.Append("<br />Question Page:" + page.ToJson()); 
    } 
} 

的代碼似乎有點冗長和複雜的 - 我只是想知道是否有這樣做的更好的辦法?由於

回答

0

假設profilesCollection的數據類型是MongoCollection <BsonDocument>,你可以縮短代碼,所以是這樣的:

 var profileDocument = profilesCollection.FindOneById(binaryId); 
     foreach (BsonDocument page in profileDocument["pages"].AsBsonArray) { 
      if (page["pagetype"].AsString == "question") { 
       sb.Append("<br />Question Page:" + page.ToJson()); 
      } 
     } 
+0

感謝改善。我真的希望有一種方法可以通過使用諸如profileDocument [「pages」]之類的語法來對內存中的對象執行查詢。Filter(「{pagetype:」question「})但看起來好像沒有'不管怎樣,謝謝。 – Journeyman 2011-05-11 10:53:02