I have a MongoDB collection named “Applicants” with documents containing information about applicants, including their last name, type, and an array of phone numbers with different types like “home”, “cell”, and “office.”
Here’s a sample JSON representation of an “Applicant” document:
{
"_id": ObjectId("61791ecf2abf206fd5e5e322"),
"LastName": "Smith",
"Type": "P",
"PhoneNumbers": [
{ "Type": "home", "Value": "111-111-1111" },
{ "Type": "cell", "Value": "222-222-2222" },
{ "Type": "office", "Value": "333-333-3333" }
]
}
Now, I need to perform a query to find applicants with specific phone numbers, e.g., “home” and “cell” phone numbers. I am using the MongoDB C# driver and want to use FilterDefinition for this purpose.
I have tried using ElemMatch method with multiple conditions, but it doesn’t seem to work as expected. Here’s my current attempt:
var filterBuilder = Builders<Applicant>.Filter;
var homePhoneFilter = filterBuilder.Eq("PhoneNumbers.Type", "home") & filterBuilder.Eq("PhoneNumbers.Value", "111-111-1111");
var cellPhoneFilter = filterBuilder.Eq("PhoneNumbers.Type", "cell") & filterBuilder.Eq("PhoneNumbers.Value", "222-222-2222");
var queryFilter = homePhoneFilter & cellPhoneFilter;
Unfortunately, this doesn’t return any results, and I suspect that combining the homePhoneFilter and cellPhoneFilter using & might not be the right approach.
Rendered Query:
following is expected render query
{
"PhoneNumbers": {
"$elemMatch": { "$and": [ { "Type": "home" }, { "Value": "111-111-1111" } ], "$and": [ { "Type": "cell" }, { "Value": "222-222-2222" } ] }
}
}