2013-02-08 51 views
1

我的情況如下:我有一個文檔,裏面有一個文檔數組,代表用戶加入的應用程序(如圖所示)。如何從子文檔數組中檢索一個特定元素?

Document Example

我需要找回根據應用程序的名稱由用戶只需一個文檔......我寫了下面的代碼和它的作品...但它會檢索所有應用程序。怎麼做只返回一個?

public Application GetUserApplication(string username) 
     { 
      var query = Query.And(Query.EQ("UserName", username), Query.ElemMatch("Applications", 
       Query.EQ("Key", this.applicationKey))); 

      MongoCursor<BsonDocument> cursor = this.users.FindAs<BsonDocument>(query); 

      cursor.SetFields(new string[]{ "Applications" }); 
      cursor.SetLimit(1); 

      var it = cursor.GetEnumerator(); 

      var apps = it.MoveNext() ? it.Current["Applications"].AsBsonArray : null; 

      ... 
     } 

回答

5

您需要的$位置操作者添加到您的SetFields投影找出匹配元素的索引:

cursor.SetFields(new string[]{ "Applications.$" }); 

順便說一句,你可以使用的更簡潔的語法:

cursor.SetFields("Applications.$"); 
+0

非常感謝! :) – 2013-02-08 21:02:12