Drobfr
Drobfr

Reputation: 11

Querying an array of arrays with the MongoDB C# driver

My document look like :

"ID" : "fruit1",
"Keys" : [
           ["apple", "carrot"]
           ["banana"]
         ]

How do I query for Keys = "carrot" using MongoDB C# driver?

I can do it in shell :

db.multiArr.find({'Keys':{$elemMatch:{$elemMatch:{$in:['carrot']}}}})

I Found it from here : Querying an array of arrays in MongoDB

But I don't have succeed written it using c# driver.

Upvotes: 1

Views: 1350

Answers (2)

Drobfr
Drobfr

Reputation: 11

I succeed with something not very biutifull :

var q = Query.ElemMatch("Keys", Query.In("$elemMatch", new List<BsonValue> { "carrot" }));

Upvotes: 0

Larry Battle
Larry Battle

Reputation: 9178

Try something like this.

Note: I didn't test this.

MongoClient client = new MongoClient(); // connect to localhost
MongoServer server = client.GetServer();
var db = server.GetDatabase("foo");
var col = db.GetCollection<RawBsonDocument>("multiArr");

// Query = {'Keys':{$elemMatch:{$elemMatch:{$in:['carrot']}}}}
BsonDocument query = new BsonDocument{ 
    "Keys", new BsonDocument {
      "$elemMatch", new BsonDocument {
          "$elemMatch", new BsonDocument {
              "$in", new BsonArray().Add("carrot")
          }
      }
    }
};
col.Find(query);

More info: http://docs.mongodb.org/ecosystem/tutorial/use-csharp-driver/#csharp-driver-tutorial

Upvotes: 1

Related Questions