Mongodb recursive query

后端 未结 1 1858
星月不相逢
星月不相逢 2021-02-14 12:34

I have the following schema in my taxon collection :

{ 
  \"_id\": 1, 
  \"na\": [ \"root_1\",
        \"root_2\",
        \"root_3\" ], 
  \"pa\":         


        
1条回答
  •  后悔当初
    2021-02-14 13:01

    You can try below aggregation.

    Stages $match - $graphLookup - $project.

    $reduce to pick the first element from the each of $graphLookup nameList's na array.

    db.taxon.aggregate([{
        $match: {
            _id: {
                $in: listId
            }
        }
    }, {
        $graphLookup: {
            from: "taxon",
            startWith: "$_id",
            connectFromField: "pa",
            connectToField: "_id",
            as: "nameList"
        }
    }, {
        $project: {
            nameList: {
                $reduce: {
                    input: "$nameList",
                    initialValue: [],
                    in: {
                        "$concatArrays": ["$$value", {
                            $slice: ["$$this.na", 1]
                        }]
                    }
                }
            }
        }
    }])
    

    0 讨论(0)
提交回复
热议问题