MongoDB C#查询包含属性值的对象数组 [英] MongoDB C# Query Array of Objects that contain a property value

查看:59
本文介绍了MongoDB C#查询包含属性值的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档中有一个数组属性.让我们将其命名为arrayProperty之类的东西:

My documents have an array property in them. Lets call it arrayProperty something like this:

 {
  _id: mongoObjectIdThingy,
  arrayProperty: [
    {string1: "aString",otherProperty:"somethingelse"},
    {string1: "aString2",otherProperty:"somethingelse"}
  ]
}

我正在使用mongodb c#驱动程序.我想查找包含任何string1值列表的所有文档.例如说我有一个字符串列表:

I'm using the mongodb c# driver. I want to find all documents that contain any of a list of string1 values. For example say I have a list of strings:

["a","b","aString"]

我希望查询返回上述文档.我已经尝试过了:

I want the query to return the above document. I've tried this:

    var builder = Builders<MyObject>.Filter;

    var listToFind = new List<string>{"a","b","aString"};


    return builder.ElemMatch(o => o.arrayProperty,
        d => listToFind.Contains(d.string1));

但是有一个例外:

不支持的过滤器:包含(value(System.Collections.Generic.List`1 [System.String]))

Unsupported filter: Contains(value(System.Collections.Generic.List`1[System.String]))

似乎我无法在驱动程序的过滤器表达式中执行一个包含linq表达式.如何使用C#在mongoDB中编写这种查询?

It seems like I can't do a contains linq expression in the driver's filter expression. How does one write this type of query in mongoDB with C#?

推荐答案

我相信您正在寻找 In FilterDefinition,它将使您的Builder看起来像这样;

I believe you are looking for the In FilterDefinition, which would make your Builder look like this;

return Builders<MyObject>.Filter.ElemMatch(
            o => o.arrayProperty,
            Builders<ArrayProperty>.Filter.In(y => y.string1, listToFind));

这将建立此查询

db.MyObject.find({ "arrayProperty" : { "$elemMatch" : { "string1" : { "$in" : ["a", "b", "aString"] } } } })

要使用正则表达式,您必须建立一个不同的查询(我不在喝咖啡,因此没有任何保证)

To be able to use the Regex you would have to build a different query (I'm not on coffee so this is without any warranty)

        var listToFind = new List<string> { "a", "b", "astring" };

        var regexList = listToFind.Select(x => new BsonRegularExpression(x, "i"));

        var filterList = new List<FilterDefinition<MyObject>>();
        foreach (var bsonRegularExpression in regexList)
        {
            FilterDefinition<MyObject> fil = Builders<MyObject>.Filter.ElemMatch(o => o.arrayProperty, Builders<ArrayProperty>.Filter.Regex(
                 x => x.string1,
                 bsonRegularExpression));

            filterList.Add(fil);
        }


        var orFilter = Builders<MyObject>.Filter.Or(filterList);

        var result = collection.Find(orFilter).ToList();

建立以下查询

db.MyObject.find({ "$or" : [{ "arrayProperty" : { "$elemMatch" : { "string1" : /a/i } } }, { "arrayProperty" : { "$elemMatch" : { "string1" : /b/i } } }, { "arrayProperty" : { "$elemMatch" : { "string1" : /astring/i } } }] })

这篇关于MongoDB C#查询包含属性值的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆