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.

Community
  • 1
  • 1
Drobfr
  • 11
  • 3
  • possible duplicate of [Using both $in and $elemMatch using the C# Driver](http://stackoverflow.com/questions/22176263/using-both-in-and-elemmatch-using-the-c-sharp-driver) – i3arnon Sep 08 '14 at 20:02
  • You basically can't in a safe way. – i3arnon Sep 08 '14 at 20:02

2 Answers2

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

Larry Battle
  • 9,008
  • 4
  • 41
  • 55
0

I succeed with something not very biutifull :

var q = Query.ElemMatch("Keys", Query.In("$elemMatch", new List<BsonValue> { "carrot" }));
Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79
Drobfr
  • 11
  • 3
  • How can query the Keys array if it was an object array instead of an string array ? – Misi Sep 27 '17 at 08:29