mongodbmongodb-querymongodb-java

query the value of a sub document in mongodb


I'm using the Java driver with a document that looks like this (a real test example):

{
    "_id" : ObjectId("5207fe359b88bfa6f90a82b0"),
    "meta_id" : "d6eb1b13-50c7-473f-8348-b5a638a542a0",
    "name" : "Fake Name Inc.",
    "created" : ISODate("2013-08-11T21:12:21.533Z"),
    "members" : {
        "5207fe359b88bfa6f90a82af" : [
            "Admin",
            "User"
        ]
    }
}

I want to select the string array at the path "members.5207fe359b88bfa6f90a82af" (which is a list of roles). I'm at a loss as to how to do that. It looks like a projection would work here, but I'm new enough to Mongo that the way the projection is written is not obvious.

I can of course load the whole object or maybe even just the "members" field, but I think I should be able to select just exactly the data I'm after.

So, does anyone have an idea of how such a query would be written?

Note: This question suggests that maybe I need to change the structure of the document to make things easier: MongoDB - Query by sub-tree


Solution

  • You can use dot notation in the projection parameter of find to do this. In the shell:

    db.test.find(
        {_id : ObjectId("5207fe359b88bfa6f90a82b0")},
        {'members.5207fe359b88bfa6f90a82af': 1, _id: 0})
    

    Returns:

    {
      "members": {
        "5207fe359b88bfa6f90a82af": [
          "Admin",
          "User"
        ]
      }
    }