not sure how to use ElemMatch in c# for MongoDb (newest driver version)

chrisb picture chrisb · Jan 12, 2016 · Viewed 7.2k times · Source

I have a MongoDB collection in the following format:

{ 
    "_id" : ObjectId("5692a3397d7518330416f8e5"), 
    "supertagname" : "xxx", 
    "inclusions" : [
        "test", 
        "blabla"
    ], 
    "exclusions" : [ ]
}

and I am trying to query for all documents where the array "inclusions" contains the value I am looking for. Here is the code

string t = "blabla"; // the string value I am looking for

filter = Builders<BsonDocument>.Filter.ElemMatch(
    "inclusions", Builders<BsonDocument>.Filter.Eq("inclusions", t));

var matches = dictCollection.Find(filter).ToList();

foreach (BsonDocument doc in matches) {}

matches.count is always 0. What am I doing wrong?

Thanks

Answer

Peter picture Peter · Jan 12, 2016

I think you can do this more simply with a filter like this:

var filter = Builders<BsonDocument>.Filter.AnyEq("inclusions", t);

This will filter for the documents where the inclusions array contains the value you're looking for.

http://mongodb.github.io/mongo-csharp-driver/2.2/reference/driver/definitions/#array-operators