【问题标题】:How to retrieve only one specific element from subdocument array?如何从子文档数组中仅检索一个特定元素?
【发布时间】:2013-02-08 20:45:47
【问题描述】:

我的情况如下:我有一个文档,其中包含一个文档数组,表示用户加入的应用程序(如图所示)。

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

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;

            ...
        }

【问题讨论】:

    标签: c# arrays mongodb projection


    【解决方案1】:

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

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

    顺便说一句,您可以使用不那么混乱的语法:

    cursor.SetFields("Applications.$");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-24
      • 1970-01-01
      相关资源
      最近更新 更多