Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I 'AND' multiple $elemMatch clauses with C# and MongoDB?

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?

like image 457
Travis Stafford Avatar asked Jun 07 '11 14:06

Travis Stafford


1 Answers

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")));
like image 109
Andrew Orsich Avatar answered Oct 31 '22 14:10

Andrew Orsich