I am using the 10Gen sanctioned c# driver for mongoDB for a c# application and for data browsing I am using Mongovue.
Here are two sample document schemas:
{
"_id": {
"$oid": "4ded270ab29e220de8935c7b"
},
"Relationships": [
{
"RelationshipType": "Person",
"Attributes": {
"FirstName": "Travis",
"LastName": "Stafford"
}
},
{
"RelationshipType": "Student",
"Attributes": {
"GradMonth": "",
"GradYear": "",
"Institution": "Test1",
}
},
{
"RelationshipType": "Staff",
"Attributes": {
"Department": "LIS",
"OfficeNumber": "12",
"Institution": "Test2",
}
}
]
},
{
"_id": {
"$oid": "747ecc1dc1a79abf6f37fe8a"
},
"Relationships": [
{
"RelationshipType": "Person",
"Attributes": {
"FirstName": "John",
"LastName": "Doe"
}
},
{
"RelationshipType": "Staff",
"Attributes": {
"Department": "Dining",
"OfficeNumber": "1",
"Institution": "Test2",
}
}
]
}
I need a query that ensures that both $elemMatch criteria are met so that I can match the first document, but not the second. The following query works in Mongovue.
{
'Relationships': { $all: [
{$elemMatch: {'RelationshipType':'Student', 'Attributes.Institution': 'Test1'}},
{$elemMatch: {'RelationshipType':'Staff', 'Attributes.Institution': 'Test2'}}
]}
}
How can I do the same query in my c# code?
There is no way to build above query using c# driver (at least in version 1.0).
But you can build another, more clear query, that will return same result:
{ "Relationships" :
{ "$elemMatch" :
{ "RelationshipType" : "Test",
"Attributes.Institution" : { "$all" : ["Location1", "Location2"] }
}
}
}
And the same query from c#:
Query.ElemMatch("Relationships",
Query.And(
Query.EQ("RelationshipType", "Test"),
Query.All("Attributes.Institution", "Location1", "Location2")));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With