[英]How to retrieve only one specific element from subdocument array?
My case is the following: I have a document with a document array inside it representing applications that user joined (as shown in Figure). 我的情况如下:我有一个文档,其中包含一个文档数组,该文档数组表示用户加入的应用程序(如图所示)。
I need retrieve just one document by user according application name... I wrote the following code and it works... But it retrieves all applications. 我只需要根据应用程序名称按用户检索一个文档...我编写了以下代码,它可以工作...但是它可以检索所有应用程序。 How to do that return just one?
如何做到只返回一个?
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;
...
}
You need to add the $
positional operator to your SetFields
projection to identify the index of the matched element: 您需要将
$
位置运算符添加到SetFields
投影中,以标识匹配元素的索引:
cursor.SetFields(new string[]{ "Applications.$" });
BTW, you can use the less cluttered syntax of: 顺便说一句,您可以使用以下较为简洁的语法:
cursor.SetFields("Applications.$");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.