mongodb c# select specific field dot notation

2019-08-14 01:59发布

问题:

In addition for my previous question: mongodb c# select specific field.

I'm writing a generic method for selecting a specific field.

the requirements are:

  1. Field can be of any type
  2. Return type is T
  3. Field can be inside a sub field
  4. Field can be inside array items - in that case its OK to select the specific field of all the items in the array

for shorts, im looking for the "select" / dot notation capability. for example:

the wanted method:

T GetFieldValue<T>(string id, string fieldName)

the document:

persons
{
  "id": "avi"
  "Freinds" : [
    {
      "Name" : "joni",
      "age" : "33"
    },
    {
      "Name" : "daniel",
      "age" : "27"
    }]
}

The goal is to call the method like this:

string[] myFriends = GetFieldValue<string[]>("avi", "Freinds.Name");
myFriends == ["joni","daniel"]

as far as i know, using projection expression with lambda is no good for items in array, I was thinking more dot notation way.

note: I'm using the new c# driver (2.0)

Thanks A lot.

回答1:

I don't see good approach with don notation in string, because it has more issues with collections than generic approach:

For example Persion.Friends.Name

  1. Which element is array in this chain?
  2. You should apply explicit conversion for collection elements (possible place of bugs)

Generic methods are more reliable in support and using:

var friends = await GetFieldValue<Person, Friend[]>("avi", x => x.Friends);
var names = friends.Select(x=>x.Name).ToArray();