Recursive search on a collection in MongoDB

后端 未结 2 1644
自闭症患者
自闭症患者 2020-12-18 21:15

I have a list of documents in MongoDB with tree structure, where Model Tree Structures with Parent References pattern used. I want a single aggregation query which returns a

2条回答
  •  甜味超标
    2020-12-18 22:09

    Starting from MongoDB 3.4, we can do this with the Aggregation Framework.

    The first and most important stage in our pipeline is the $graphLookup stage. $graphLookup allows us to recursively match on the "parent" and "name" field. As result, we get the ancestors of each "name".

    The next stage in the pipeline is the $match stage where we simply select the "name" we are interested in.

    The final stage is the $addFields or $project stage where we apply an expression to the "ancestors" array using the $map array operator.

    Of course with the $reverseArray operator we reverse our array in order to get the expected result.

    db.collection.aggregate(
        [ 
            { "$graphLookup": { 
                "from": "collection", 
                "startWith": "$parent", 
                "connectFromField": "parent", 
                "connectToField": "name", 
                "as": "ancestors"
            }}, 
            { "$match": { "name": "D" } }, 
            { "$addFields": { 
                "ancestors": { 
                    "$reverseArray": { 
                        "$map": { 
                            "input": "$ancestors", 
                            "as": "t", 
                            "in": { "name": "$$t.name" }
                        } 
                    } 
                }
            }}
        ]
    )
    

提交回复
热议问题