Search code examples
c#asp.net-mvc-3mongodbmongodb-.net-drivermongodb-query

How to query a document within a document in MongoDB?


OK so I have this document structure within my database:

Message: {
    uid: "id",
    subject: "I AM A MESSAGE!",
    body: "ASDF",
    recipients: {
        name: "John Doe",
        hasRead: "true"
    }
}

How do I use the C# driver to write a query for items that only John Doe has received? I'm using the MongoDB driver v1.3.1.


Solution

  • In the shell, the query would be

    db.Message.find({"recipients.name" : "John Doe"});
    

    The C# query depends on the data structure you're using in C#. I'm irritated that recipients is plural, but the json is not an array. Since there are different ways of mapping C# collections to JSON, I can't present the C# query in linq form.

    However, given the data structure you posted, this should work:

    db.GetCollection("Message").Find(Query.EQ("recipients.name", "John Doe"));