0

My document has a property that is of the type List<string>. I want to return all documents from a collection where a set of strings match any item from this List<string> property.

I would like to construct this like the following question, but in C#:

MongoDB find where key equals string from array

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)
4

2 回答 2

1

如果由于某种原因您不想使用 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);

如果您想仔细检查本机 MongoDB 查询的外观,您可以使用:

var json = query.ToJson();

在这种情况下,这表明等效的 MongoDB 查询是:

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

如果这不是您要查找的本机 MongoDB 查询,请告诉我。

ps 1.5 版中有一个新的查询生成器,而 QueryComplete 现已过时。

于 2012-07-25T15:37:59.643 回答
1

看起来您正在寻找的内容如下所述:

包含任何

此方法用于测试数组(或类似数组)字段或属性是否包含任何提供的值。

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 }));
于 2012-07-25T07:06:23.960 回答