1

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.

2

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

I succeed with something not very biutifull :

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

1 Comment

How can query the Keys array if it was an object array instead of an string array ?

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.