如何在嵌套文档下获取所有类别?

时间:2017-02-20 11:20:15

标签: mongodb mongoose

我在mongo db中有以下json对象,文档中有大约300个对象,在ticket.seating下检索所有 category 的查询是什么,

 {   "_id": "58a1ddcb8850c027298c4dc8",   "name": "Listing 1",  
 "description": "",   "ticket": {
     "amount": 2,
     "type": "electronic",
     "splitType": 2,
     "seating": [
       {
         "category": 1,
         "section": 2,
         "row": 2
       },
       {
        "category": 3,
         "section": "uiui",
         "row": 33
       }
     ]   },   "metadata": {
     "user": {},
     "event": {},
     "venue": {}   },   "listingId": "aabb1cb6-4e79-4d48-9451-e5247230d397" }

预期输出:

1,3

2 个答案:

答案 0 :(得分:3)

您可以使用MongoDB Distinct功能。如下面的示例所示

db.getCollection('collection_name').distinct("ticket.seating.category");

它将为您提供数组中所有不同的类别,如[1,3]

答案 1 :(得分:2)

这应该可以解决问题

db.collection.aggregate([
   {
      $unwind:"$ticket.seating"
   },
   {
      $group:{
         _id:null,
         category:{
            $push:"$ticket.seating.category"
         }
      }
   }
])

输出:

{ "_id" : null, "category" : [ 1, 3 ] }