$filter upto 3 nested level in mongodb

后端 未结 1 1358
你的背包
你的背包 2020-12-21 15:51

I have a below collection

[
  {
    \"Array1\": [
      {
        \"Array2\": [
          {
            \"name\": \"6666\",
            \"Array3\": [
                


        
相关标签:
1条回答
  • 2020-12-21 16:22

    Basically you have to use $filter for each level to apply your condition and $map for each array that has nested array inside. That's because you want to pass filtered array to the output. So there will be 3 filters and 2 maps. Indentations might be really helpful in this case. Try:

    db.collection.aggregate([
        {
            $project: {
                Array1: {
                    $map: {
                        input: { $filter: { input: "$Array1", as: "a1", cond: { $eq: ["$$a1.name", "old apartment" ] } } },
                        as: "a1",
                        in: {
                            name: "$$a1.name",
                            Array2: {
                                $map: {
                                    input: { $filter: { input: "$$a1.Array2", as: "a2", cond: { $eq: [ "$$a2.name", "6666" ] } } },
                                    as: "a2",
                                    in: {
                                        name: "$$a2.name",
                                        Array3: { $filter: { input: "$$a2.Array3", as: "a3", cond: { $eq: [ "$$a3.nest", "nokia" ] } } }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    ])
    

    Mongo playground

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