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)

2 Answers 2

1

Looks like what you are looking for is described here:

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 }));
Sign up to request clarification or add additional context in comments.

1 Comment

yes ContainsAny works perfectly. I see that in the docs now. Thanks
1

If for some reason you prefer not to use LINQ, you can use the query builder to write it like this:

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:

var json = query.ToJson();

which in this case shows that the equivalent MongoDB query is:

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

If this is not the native MongoDB query you were looking for let me know.

p.s. There is a new query builder in version 1.5 and QueryComplete is now obsolete.

1 Comment

Thanks for the additional information, and the ToJson() method. I will use that in the shell for testing going forward. Perhaps this should be an additional question on SO, but is there any instance where the Linq query ContainsAny would be slower than the above QueryBuilder or do they generate the same MongoDB query? This thread has been helpful in my understanding Linq / Querybuilder / Mongodb shell queries

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.