How to return a nested document in an array

后端 未结 1 756
半阙折子戏
半阙折子戏 2021-01-24 18:51

I have documents with a schema such as follows:

{
    \"user_id\": 123,
    \"services\":[
         {\"name\": \"test\",
          \"data\": ...
         },
             


        
1条回答
  •  深忆病人
    2021-01-24 19:02

    You need to run $unwind to get single document from services and $replaceRoot to promote it to root level:

    db.guilds.aggregate([
        {
            $match: { user_id: 123, "services.name": "test" }
        },
        {
            $unwind: "$services"
        },
        {
            $match: { "services.name": "test" }
        },
        {
            $replaceRoot: { newRoot: "$services" }
        }
    ])
    

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