【发布时间】:2017-12-03 12:55:15
【问题描述】:
我有一些课。
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 示例文档:
{
"_id": "1",
"MyList": [{
"text":"Element 0"
},{
"text":"Element 1"
}]
}
现在我只想检索元素 0。我使用 Projection 编写了以下代码:
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(); -
如果我明确地写一个函数,它就会起作用:
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<yourclass>.Projection.ElemMatch(...)会满足您的需求?或者,如果您只想要第一个,Builders<yourclass>.Projection.Slice(...) -
是的,Slice 可以,但我测试了一下,它也会返回 MyClass 的其他字段。
标签: .net mongodb projection