【问题标题】:Get a specific array element using Projection of MongoDB .Net Driver使用 MongoDB .Net 驱动程序的投影获取特定的数组元素
【发布时间】: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();

有人知道为什么吗?以及如何使用该元素的索引获取特定的数组元素?

更新:

我做了一些实验,发现了以下几点:

  1. 如果只需要数组的第一个元素,以下将起作用。

    //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();
    
  2. 如果我明确地写一个函数,它就会起作用:

    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&lt;yourclass&gt;.Projection.ElemMatch(...) 会满足您的需求?或者,如果您想要第一个,Builders&lt;yourclass&gt;.Projection.Slice(...)
  • 是的,Slice 可以,但我测试了一下,它也会返回 MyClass 的其他字段。

标签: .net mongodb projection


【解决方案1】:

在 Mongodb 控制台(javaScript)中,您可以使用:

db.foo.find({_id:"1"}).map(function(u){return u.MyList[0].text})

你可以尝试在C#中转换这个,一定有一些函数。

【讨论】:

  • 查看我的更新。我找到了一种通过编写显式函数来使其工作的方法。我不明白的是,我认为lambda表达式应该和写一个函数差不多。
猜你喜欢
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 2020-01-25
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多