【问题标题】:How can I search a collection of several list<T> with queries?如何使用查询搜索多个 list<T> 的集合?
【发布时间】:2014-07-31 14:44:06
【问题描述】:

我是 MongoDb 的新手,所以我只是在玩弄它。

现在我创建了一个MongoDbCollection&lt;MyDocument&gt;,它存储了很多MyDocumentsMyDocument 包含许多不同的参数,如 IDNameBirthdatexData、...

class MyDocument
{
    public MyDocument() { }

    public ObjectID Id { get; set; }
    public string Name { get; set; }
    public string Birthdate { get; set; }
    public BsonDocument[] xData { get; set; } // just additional data
}

如果我在MongoDbCollection 查询文档...

MongoCursor elements = collection.Find(Query.And(MyQueryInput));

例如:查找名称“Peter”的查询。我将得到一个列表,其中包含“名称”等于“彼得”的所有元素。它还从“xData”BsonDocument 返回“名称”字段。到目前为止一切正常。

现在我想创建一个MongoDbCollection&lt;List&lt;MyDocument&gt;&gt;,所以它是一个包含MyDocuments 的列表集合。这就是为什么我定义了一个包含MongoIDList 的新类:

class MyMongoList
{
    public MyMongoList() { }

    public ObjectID Id() { get; set; }
    public List<MyDocument> list { get; set; }
}

我可以将MyDocuments 添加到列表中并将列表添加到集合中,但是如果我循环遍历,则没有任何反应。

MongoCursor elements = collection.Find(Query.And(MyQueryInput));
foreach(MyMongoList<MyDocument> list in elements)
{
    Console.WriteLine("something"); // nothing happends here
}

我想知道为什么“元素”是空的。

[问题] 是否可以像上面一样查询所有列表?

[问题] 我是否必须在 MyMongoList 类中添加一些东西,MongoDb 可以在 c#Lists 中搜索?

目前,我不知道出了什么问题。我感觉它与 MongoDb Serialization 有关,但直到现在我还没有找到实现它的方法。

【问题讨论】:

    标签: c# list mongodb serialization


    【解决方案1】:

    我发现了我的错误。我只需要使用 Query.ElemMatch() 方法。举例说明here

    要查询一个列表,我使用了以下代码:

    MongoCursor elements = collection.Find(Query.ElemMatch("list",MyQueryInput));
    

    现在 MongoDB 将集合中的所有列表(至少具有 1 个符合条件的 MyDokument)放入元素中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-29
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      • 2014-07-31
      相关资源
      最近更新 更多