【问题标题】:Get key value pair result of activities in Mongodb获取MongoDB中活动的键值对结果
【发布时间】:2019-07-23 06:43:13
【问题描述】:

获取活动的键值对结果。将第一个元素项下的所有活动作为键。

输入

[
 {
   "_id": "diamond",
   "activities": [
     [
       {
         "term": "11",
         "sport_name": "football"
       }
     ]
   ]
 },
 {
   "_id": "topaz",
   "activities": [
     [
       {
         "term": "12",
         "sport_name": "football"
       }
     ],
     [
       {
         "term": "11",
         "sport_name": "football"
       },
       {
         "term": "11",
         "sport_name": "hand ball"
       }
     ]
   ]
 }
]

输出

[
 {
   "_id": "diamond",
   "activities": [
       {
           "11": [
               {
                   "term": "11",
                   "sport_name": "football"
               }
           ]
       }
   ]
 },
 {
   "_id": "topaz",
   "activities": [
       {
           "12": [
               {
                 "term": "12",
                 "sport_name": "football"
               }
           ]
       },
       {
           "11": [
               {
                 "term": "11",
                 "sport_name": "football"
               },
               {
                 "term": "11",
                 "sport_name": "hand ball"
               }
           ]
       }
   ]
 }
]

【问题讨论】:

    标签: mongodb nosql mongodb-query aggregation-framework


    【解决方案1】:

    你可以使用下面的聚合

    db.collection.aggregate([
      { "$project": {
        "activities": {
          "$arrayToObject": {
            "$map": {
              "input": "$activities",
              "in": {
                "k": { "$arrayElemAt": ["$$this.term", 0] },
                "v": "$$this"
              }
            }
          }
        }
      }}
    ])
    

    MongoPlayground

    【讨论】:

      猜你喜欢
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-21
      • 1970-01-01
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多