从子文档返回字段数组

时间:2016-11-15 04:45:21

标签: mongodb mongodb-query aggregation-framework

任何人都可以请帮助我想查询mongo来解开数组,我正在使用mongdb本机驱动程序我的收集文件如下,也请忽略我的objectId它只是为了样本

{  
      "_id":ObjectId(123),
      "name":"Sam",
      "age":20,
      "hobbiesDetail":[  
         {  
            "description":"FootBall",
            "level":"20%"
         },
         {  
            "description":"Cricket",
            "level":"80%"
         }
      ]
   },
   {  
      "_id":ObjectId(124),
      "name":"Ted",
      "age":26,
      "hobbiesDetail":[  
         {  
            "description":"FootBall",
            "level":"20%"
         }
      ]
   }

我的预期输出是

[  
   {  
      "name":"Sam",
      "age":20,
      "hobbies":"Football,Cricket"
   },
   {  
      "name":"Ted",
      "age":26,
      "hobbies":"Football"
   }
]

我只是想放松我的数组并在一个查询中的爱好描述之间添加一个逗号,Thanx以获得任何帮助

1 个答案:

答案 0 :(得分:1)

您需要的只是$project$map数组运算符。

db.collection.aggregate([
    { "$project": { 
        "name": 1, 
        "age": 1, 
        "hobbies": { 
            "$map": { 
                "input": "$hobbiesDetail", 
                "as": "hobby", 
                "in": "$$hobby.description" 
            } 
        } 
    }}
])