简体   繁体   中英

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"), eg "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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM