如何从子文档数组中只检索一个特定元素?

Luc*_*ssi 1 c# arrays projection mongodb

我的情况如下:我有一个文档,里面有一个文档数组,表示用户加入的应用程序(如图所示).

文档示例

我需要用户根据应用程序名称检索一个文档...我编写了以下代码并且它可以工作......但它检索所有应用程序.怎么做只返回一个?

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;

            ...
        }
Run Code Online (Sandbox Code Playgroud)

Joh*_*yHK 5

您需要将$位置运算符添加到SetFields投影中以标识匹配元素的索引:

cursor.SetFields(new string[]{ "Applications.$" });
Run Code Online (Sandbox Code Playgroud)

顺便说一下,你可以使用较简洁的语法:

cursor.SetFields("Applications.$");
Run Code Online (Sandbox Code Playgroud)