简体   繁体   English

使用C#驱动程序在MongoDB中搜索对象数组

[英]Searching an array of objects in MongoDB using the C# Driver

Following the advice of this article I created a blob index on an array of objects in my documents. 按照本文的建议,我在文档中的对象数组上创建了一个Blob索引。 For example: 例如:

{
...
    "itemID" : 37,
    "MetaData" : [ 
        {
            "FileExtension" : "TXT"
        }, 
        {
            "EmailSubject" : "GAS DESK HEAD MEETING"
        }, 
        {
            "DocumentType" : "EMAIL"
        }, 
        {
            "Date_BestEmailSent" : ISODate("2001-01-26T04:11:32.000Z")
        }, 
        {
            "Date_ParentDate_BestDate" : ISODate("2001-01-26T04:11:32.000Z")
        }, 
        ...
        ],
    ...
}

I'm now parsing a search tree in C# to build a query using the MongoDB C# driver: 我现在正在解析C#中的搜索树,以使用MongoDB C#驱动程序来构建查询:

IMongoQuery expression; 
switch (leaf.Op)
{
    case SearchOperation.Equals:
        expression = Query.EQ(leaf.Field, leaf.Value);
        break;
    case SearchOperation.Contains:
        expression = Query.Matches(leaf.Field, leaf.Field);
        break;
    ...
}

if (_rootLevelFields.Contains(leaf.Field))
{
    return expression;
}
return Query.ElemMatch("MetaData", expression);

In this case, if my search criteria was FileExtension EQ 'TXT' It would run: 在这种情况下,如果我的搜索条件是FileExtension EQ 'TXT' ,它将运行:

db.test.find({"MetaData": {$elemMatch: {"FileExtension":"TXT"}}})

This runs very slowly and the explain indicates it's scanning all records and not using my Index. 这运行非常缓慢,并且解释说明它正在扫描所有记录,而不使用我的索引。 If I manually run: 如果我手动运行:

db.test.find({"MetaData": {"FileExtension":"TXT"}})

It uses the index and runs much faster. 它使用索引并且运行更快。 In this case it appears I don't want to use ElemMatch but the MongoDB Builder namespace doesn't seem to accommodate this type of query eg 在这种情况下,我似乎不想使用ElemMatch,但是MongoDB Builder命名空间似乎无法容纳这种查询,例如

Query.EQ("MetaData", expression);

is not syntactically correct. 在语法上不正确。 I've poured over the documentation and even the MongoDB driver source code but can't find how to do what I want. 我已经遍历了文档甚至MongoDB驱动程序源代码,但是找不到如何做我想要的事情。 Am I missing something obvious? 我是否缺少明显的东西?

The EQ method accepts only BSONValue as a parameter, but you're trying to pass a IMongoQuery instance. EQ方法仅接受BSONValue作为参数,但是您正在尝试传递IMongoQuery实例。

In your second query you're basically searching this document in MetaData array : 在第二个查询中,您基本上是在MetaData数组中搜索此文档:

{"FileExtension":"TXT"}

You will need to create a new BsonDocument and pass it into your EQ method: 您将需要创建一个新的BsonDocument并将其传递到您的EQ方法中:

Query.EQ("MetaData", new BsonDocument(leaf.Field, leaf.Value));

You can check the documentation for EQ method for more details. 您可以查看EQ方法文档以了解更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM