Search code examples
c#asp.netarraysmongodbprojection

Is it possible retrieve only one specific field of a subdocument from an array?


Suppose I have following document structure on a MongoDB collection:

{
  "Applications" : [{
      "JoinDate" : new Date("10/2/2013 18:06:30"),
      "Key" : "shtube",
      "Roles" : ["Administrator", "Moderator"]
    }],
  "Comment" : "Cool",
  "ConfirmationKey" : "981c69fe-6fff-47d6-bb82-3b5f1deeef25",
  "CreationDate" : new Date("8/2/2013 17:43:42"),
  ...
} 

How can I retrieve (for performance issue) just "Roles" field using the SetFields() method from MongoCursor? At this time I only know retrieve subdocument and access "Roles". But I don't need entire subdocument info.


Solution

  • You can use a projection to extract just the field(s) that you want using dot notation (using the shell):

    db.myCollection.find({ "Applications.Roles" : { $exists: true } },
                 {  "Applications.Roles" : 1 })
    

    In the above example, it's just returning documents that contain the Applications.Roles structure.

    You can read more about projections here.

    FYI: You can't do a projection from C# with LINQ efficiently. It does the projection locally on the client.

    Another alternative is to use $elemMatch (however, in this case, it might not fit your needs if you aren't doing a particular query).