Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

mongodb

bson

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

like image 361
chrisb Avatar asked Jan 12 '16 18:01

chrisb


1 Answers

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

like image 166
Peter Avatar answered Oct 19 '22 16:10

Peter