私はいくつかのクラスを持っています。ここでMongoDB .Netドライバの投影を使用して特定の配列要素を取得する
public class MyClass
{
public string Id {get;set;}
public List<MyElement> MyList {get;set;} = new List<MyElement>();
//Other extra fields
}
public class MyElement
{
public string Text {get;set;}
public string AnotherField {get;set;}
}
のMyClassの私のサンプル文書です:今、私は唯一の要素0を取得したい
{
"_id": "1",
"MyList": [{
"text":"Element 0"
},{
"text":"Element 1"
}]
}
私はプロジェクションを使って以下のコードを書いた:
Expression<Func<MyClass, MyElement>> getElementZero = (c => c.MyList[0]);
Expression<Func<MyClass, List<MyElement>>> getList = (c => c.MyList);
FilterDefinition<MyClass> filter = Builders<MyClass>.Filter.Eq(p => p.Id, "1");
//This is good
List<MyElement> myList = mongoCollection.Find(filter).Project(getList).First();
//However, myElement is null after this projection
MyElement myElement = mongoCollection.Find(filter).Project(getElementZero).First();
誰もがなぜ知っていますか?そして、その要素のインデックスを使用して特定の配列要素を取得するにはどうすればよいですか?
更新:
私はいくつかの実験をしたし、次のものを見つける:
配列の最初の要素だけが望まれる場合は、次のように動作します。私は明示的に関数を記述した場合
//this will work MyElement myElement = mongoCollection.Find(filter).Project(c => c.MyList.First()).First(); //this is not going to work MyElement myElement = mongoCollection.Find(filter).Project(c => c.MyList.GetElementAt(0)).First();
、それは動作します:
db.foo.find({_id:"1"}).map(function(u){return u.MyList[0].text})
ます:MongoDBのコンソールで
public MyElement GetElementAt(MyClass c, int index) { return c.MyList[index]; } //this will work MyElement myElement = mongoCollection.Find(filter).Project(c => GetElementAt(c, someIndex)).First();
多分 'Builders .Projection.ElemMatch(...)はあなたが探していることをしますか?または、最初のものが必要な場合は、「Builders .Projection.Slice(...)」 –
john
うん、Sliceは動作しますが、私はそれをテストして、MyClassの他のフィールドも返します。 – liupro925