Spring Data Mongo - How to get the nested distinct array for nested value?

99封情书 提交于 2020-07-19 23:02:21

问题


I'm taking a reference from : Spring Data Mongo - Perform Distinct, but doesn't wants to pull embedded documents in results and asking another questions.

I want to find technology list where "subdeptCd" : "1D". How can we do that ?

{
    "firstName" : "Laxmi",
    "lastName" : "Dekate",
    .....
    .......
    .....

    "departments" : {
        "deptCd" : "Tax",
        "deptName" : "Tax Handling Dept",
        "status" : "A",
        "subdepts" : [ 
            {
                "subdeptCd" : "1D",
                "subdeptName" : "Tax Clearning",
                "desc" : "",
                "status" : "A"
                "technology" : [ 
                    {
                        "technologyCd" : "4C",
                        "technologyName" : "Cloud Computing",
                        "desc" : "This is best certficate",
                        "status" : "A"
                    }
                ]
            }
        ]
    },
},
{
    "firstName" : "Neha",
    "lastName" : "Parate",
    .....
    .......
    .....

    "departments" : {
        "deptCd" : "Tax Rebate",
        "deptName" : "Tax Rebate Handling Dept",
        "status" : "A",
        "subdepts" : [ 
            {
                "subdeptCd" : "1D",
                "subdeptName" : "Tax Clearning",
                "desc" : "",
                "status" : "A"
                "technology" : [ 
                    {
                        "technologyCd" : "9C",
                        "technologyName" : "Spring Cloud",
                        "desc" : "This is best certficate post Google",
                        "status" : "A"
                    }
                ]
            }
        ]
    },
}

回答1:


You can get distinct technologies (technology array elements) with this aggregation:

db.depts.aggregate( [
  {
       $unwind: "$departments.subdepts"
  },
  {
       $unwind: "$departments.subdepts.technology"
  },
  {
       $match: { "departments.subdepts.subdeptCd": "1D" }
  },
  {
       $group: { _id: "$departments.subdepts.technology.technologyCd", tech: { $first: "$departments.subdepts.technology" } }
  },
  {
      $replaceRoot: { newRoot: "$tech" }
  }
] )


来源:https://stackoverflow.com/questions/62260287/spring-data-mongo-how-to-get-the-nested-distinct-array-for-nested-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!