简体   繁体   English

查询以在MongoDB中查找子文档

[英]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". 我在MongoDB中有一个简单的文档,其中包含一个称为“罚款”的子文档。 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". 现在,我想通过子文档中的字符串(“ penalties”)找到文档(此处带有_id“ Cammeritz”),例如“ 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. 最好的解释是Java,但也可以,如果您只需要普通MongoDB查询的帮助。

{
    "_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 . db.collection.find( { penalties.penaltyid: '0f77d885-6597-3f47-afb1-0cee2ea3ece1' } )有关更多信息,请参见查询嵌套字段


Original answer: 原始答案:

db.collection.find( { penalties: "0f77d885-6597-3f47-afb1-0cee2ea3ece1" } ) should work. db.collection.find( { penalties: "0f77d885-6597-3f47-afb1-0cee2ea3ece1" } )应该可以正常工作。 For more see Query an Array for an Element from the mongodb docs. 有关更多信息,请参见mongodb文档中的为元素查询数组 I'm not very familiar with Java so I can't help much there. 我对Java不太熟悉,所以在那里没有太多帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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