简体   繁体   中英

Query all documents and sub-documents for a specific key in mongodb without looping

I had hard time choosing the right title for this question. I have a list of documents and sub-documents as the following

{
        "name" : "Pets",
        "subcategories" : [
            {
                "name" : "Cats",
                "fbCategories" : []
            },
            {
                "name" : "Dogs",
                "fbCategories" : []
            }
        ],
        "fbCategories" : ["Pet Services","Pet Supplies", "Animal"]
    },
    {
        "name" : "Entertainment",
        "subcategories" : [
            {
                "name" : "Music",
                "subcategories" : [
                    {
                        "name" : "Albums",
                        "fbCategories" : [ "Album"]
                    },
                    {
                        "name" : "Musicians",
                        "fbCategories" : ["Concert Tour","Musician/Band"]
                    }
                ],
                "fbCategories" : [
                    "Concert Venue",
                    "Music Chart",
                    "Music Video",
                    "Musical Instrument",
                    "Record Label",
                    "Music"
                ]
            }

In this example, we have two main categories ("Pets","Entertainment" ) and their corresponding subcategories (cats and dogs for "Pets",... ) . Although there are different levels of subcategories, but all documents/sub-documents have two keys, name and fbCategories . I want to find the fbCategories for each category/subcategory without writing a loop or multiple queries. Is there anyway to query them all within one query, the result should list the "fbCategories" for each "name" key. For example for "musicians" , it will list ["Concert Tour","Musician/Band"] , while for "Music" it will list

 ["Concert Venue","Music Chart","Music Video","Musical Instrument","Record Label","Music"]          

just look at: Finding embeded document in mongodb?

without loop, imho, this problems has not solution, because $where statement restricted in aggregation framework.

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