Search code examples
c#arraysjsonmongodbmongodb-.net-driver

Querying MongoDB nested array documents using C#


I am trying to implement the text search functionality with the nested array documents in MongoDB using C#. And I have a MongoDB collection in the below format.

{    
   "_id" : ObjectId("56c6f03ffd07dc1de805e84f"),
   "Customers" : {
            "Contact" : [ 
                           [
                             { 
                                "FirstName" : "Swetha", 
                                "LastName" : "DevAnand"
                             }
                           ]
                        ]
                   }
}

Mongo Query:

  db.test_collection.find({"Customers.Contact":{$elemMatch:{$elemMatch:{LastName: /.*Dev.*/}}}});

As in the above MongoDB query, I wanted to do a LIKE Search with the innermost array of BSON document using C#. However, I have acheived this using nested $elemMatch in Mongo Query. But while trying to do the same in C#, it expects the fieldname for every ElemMatch Query.In the above case, the innermost array of Contact field does not have any explicit field name. So far, I have tried all the below C# code to implement the scenario, but none of them helps.

var regex = new BsonRegularExpression(searchVal,"i");

query = Query.And(Query.ElemMatch("Customers.Contact", Query.And(Query.ElemMatch("LastName", Query.Matches("LastName", regex)))));
query = Query.And(Query.Matches("Customers.Contact.$.LastName",regex));
query = Query.And(Query.ElemMatch("Customers.Contact.$", Query.EQ("LastName", regex)));                 
query = Query.And(Query.ElemMatch("Customers.Contact.$", Query.Matches("LastName", regex)));
query = Query.And(Query.ElemMatch("Customers.Contact", Query.And(Query.ElemMatch("$", Query.EQ("LastName", regex)))));

Any help is really appreciated.


Solution

  • After a week of struggle, found a way. The best method to implement the above MongoDB Query is to deserialize it into a BsonDocument which in return will be passed to FindAsync as filter.

    var bQuery = "{'Customers.Contact':{$elemMatch:{$elemMatch:{LastName: /.*Dev.*/}}}}";
    var filter = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(bQuery);
    var result = collection.FindSync(filter).ToList();
    

    Thanks to Mr.Saleem. Please refer to below link for more details. How to implement MongoDB nested $elemMatch Query in C#