[英]How to retrieve only one specific element from subdocument array?
我的情況如下:我有一個文檔,其中包含一個文檔數組,該文檔數組表示用戶加入的應用程序(如圖所示)。
我只需要根據應用程序名稱按用戶檢索一個文檔...我編寫了以下代碼,它可以工作...但是它可以檢索所有應用程序。 如何做到只返回一個?
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;
...
}
您需要將$
位置運算符添加到SetFields
投影中,以標識匹配元素的索引:
cursor.SetFields(new string[]{ "Applications.$" });
順便說一句,您可以使用以下較為簡潔的語法:
cursor.SetFields("Applications.$");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.