3

I have a MongoDB collection in the following format.

{
"_id" : ObjectId("56c6f03ffd07dc1de805e84f"),
"Details" : {
    "a" : [
            [ { 
                "DeviceID" : "log0", 
                "DeviceName" : "Dev0"
              },
              { 
                "DeviceID" : "log1", 
                "DeviceName" : "Dev1"
              }
            ],
            [ { 
                "DeviceID" : "Model0", 
                "DeviceName" : "ModelName0"
              },
              { 
                "DeviceID" : "Model1", 
                "DeviceName" : "ModelName1"
              }
            ]
        ]
    }
}

And I am trying to fetch all the documents where the DeviceName in array "a" contains a particular value, say "Name0". However I could get the desired result while using below Mongo query:

db.test_collection.find({"Details.a":{$elemMatch:{$elemMatch:{DeviceName : /.*Name0.*/}}}});

Now I am struggling to implement the above query in C#. Can anyone guide me with that?

so far I have tried the below code and it was not working as expected

query = Query.And(Query.ElemMatch("Details.a", Query.And(Query.ElemMatch("DeviceName", Query.Matches("DeviceName", new BsonRegularExpression("Name0"))))));

Thanks in advance

0

1 Answer 1

8

Well, honestly writing queries in C# are bit tricky but you can always play a trick.

var bsonQuery = "{'Details.a':{$elemMatch:{$elemMatch:{DeviceName : /.*Name0.*/}}}}";
var filter = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(bsonQuery);

var result = col.FindSync (filter).ToList();

I'm deserializing a plain MongoDB queries into a BsonDocument which in return I'm passing to FindAsync as filter.

In the end, you'll have desired outcome in variable result.

Note: I'm assuming MongoDB connection has been established and variable col holds reference to MongoDB collection.

EDIT: Please see following link https://groups.google.com/forum/#!topic/mongodb-csharp/0dcoVlbFR2A. Now it's confirmed that C# driver doesn't support nameless filters so writing above query using Buidlers<BsonDocument>.Filter at moment is not supported.

Long story short, you are left with only one choice and that is to query as I mentioned above in my solution.

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

1 Comment

Wow..Great! Thtz exactly the way I want. It worked wonders. Thanx a lot Saleem..:-)

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.