Search code examples
javadatabasemongodbmongodb-querybson

Query to find a subdocument in MongoDB


Alright, i've got a simple question. I have a simple Document in MongoDB which holds a sub-document called "penalties". Now i want to find the Document (here with the _id "Cammeritz") by a String in the sub-document ("penalties"), e.g. "penaltyid = 0f77d885-6597-3f47-afb1-0cee2ea3ece1". Can you maybe help me? Best would be an explanation for Java but it is okay if you maybe just help with a normal MongoDB query.

{
    "_id" : "Cammeritz",
    "penalties" : [ 
        {
            "_id" : null,
            "date" : ISODate("2017-09-25T20:01:23.582Z"),
            "penaltyid" : "0f77d885-6597-3f47-afb1-0cee2ea3ece1",
            "reason" : "Hacking",
            "teammember" : "Luis",
            "type" : "ban"
        }, 
        {
            "_id" : null,
            "date" : ISODate("2017-09-25T20:01:23.594Z"),
            "penaltyid" : "7f5411b0-e66a-33b3-ac4f-4f3159aa88a9",
            "reason" : "Spam",
            "teammember" : "BluingFX",
            "type" : "kick"
        }
    ],
    "isBanned" : true,
    "isMuted" : false
}

Solution

  • Oops, I misread your question. You'll need to use dot notation. db.collection.find( { penalties.penaltyid: '0f77d885-6597-3f47-afb1-0cee2ea3ece1' } ) For more info see Query on a Nested Field.


    Original answer:

    db.collection.find( { penalties: "0f77d885-6597-3f47-afb1-0cee2ea3ece1" } ) should work. For more see Query an Array for an Element from the mongodb docs. I'm not very familiar with Java so I can't help much there.