Search code examples
c#arraysmongodbprojection

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).

Document Example

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;

            ...
        }

Solution

  • You need to add the $ positional operator to your SetFields projection to identify the index of the matched element:

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

    BTW, you can use the less cluttered syntax of:

    cursor.SetFields("Applications.$");