简体   繁体   English

C#mongodb其中OR列表<string>

[英]C# mongodb where OR List<string>

My document has a property that is of the type List<string> . 我的文档有一个属性为List<string>的属性。 I want to return all documents from a collection where a set of strings match any item from this List<string> property. 我想从一个集合中返回所有文档,其中一组字符串匹配此List<string>属性中的任何项目。

I would like to construct this like the following question, but in C#: 我想像下面的问题那样构造它,但是在C#中:

MongoDB find where key equals string from array MongoDB找到key等于数组中字符串的位置

I know this is off, but it's my best attempt: 我知道这是关闭的,但这是我最好的尝试:

var queryItems = new List<QueryComplete>();
queryItems.Add(Query.EQ("PropertyName", "test"));
var query= Query.Or(queryItems.ToArray());
var qd = new QueryDocument(new BsonDocument { query.ToBsonDocument() });
var result = GetCollection<CollectionName>().FindAs<Type>(qd)

Looks like what you are looking for is described here: 看起来你在寻找的是这里描述的:

ContainsAny ContainsAny

This method is used to test whether an array (or array-like) field or property contains any of the provided values. 此方法用于测试数组(或类数组)字段或属性是否包含任何提供的值。

var query =
    from c in collection.AsQueryable<C>()
    where c.A.ContainsAny(new[] { 1, 2, 3 })
    select c;
// or
var query =
    collection.AsQueryable<C>()
    .Where(c => c.A.ContainsAny(new[] { 1, 2, 3 }));

If for some reason you prefer not to use LINQ, you can use the query builder to write it like this: 如果由于某种原因您不想使用LINQ,可以使用查询构建器将其写为:

var setOfStrings = new BsonValue[] { "a", "b", "c" };
var query = Query.Or(
    Query.EQ("PropertyName", "test"),
    Query.In("List", setOfStrings)
);
var cursor = collection.FindAs<C>(query);

If you want to double check what the native MongoDB query looks like you can use: 如果要仔细检查本机MongoDB查询的外观,您可以使用:

var json = query.ToJson();

which in this case shows that the equivalent MongoDB query is: 在这种情况下,显示等效的MongoDB查询是:

{ "$or" : [
    { "PropertyName" : "test" },
    { "List" : { "$in" : ["a", "b", "c"] } }
] }

If this is not the native MongoDB query you were looking for let me know. 如果这不是您要查找的本机MongoDB查询,请告诉我。

ps There is a new query builder in version 1.5 and QueryComplete is now obsolete. ps版本1.5中有一个新的查询构建器,QueryComplete现在已过时。

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

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