【问题标题】:How could I modify the returned record format如何修改返回的记录格式
【发布时间】:2016-02-27 02:57:03
【问题描述】:

聚合后我得到了带有profile字段的嵌套结构,

我想展平配置文件结构,只保留名称字段。

我怎么能在聚合中做到这一点。

我的聚合查询和这个类似

  db.hitting_stats.aggregate(
    [
      {$lookup: {
          from: 'players', 
          localField: 'name', 
          foreignField: 'name',
          as: 'profile'
        }
      }
    ]
  );

加入聚合后的记录格式

 {"_id"=>BSON::ObjectId('566d93bb5e428410e5a3354c'),
  "author_id"=>113536670874,
  ...
  "created_time"=>"2015-11-27T09:17:07+0000",
  "profile"=>{"_id"=>BSON::ObjectId('566d93695e428410e5a33224'), "name"=>"DJ"}}

预期格式

 {"_id"=>BSON::ObjectId('566d93bb5e428410e5a3354c'),
  "author_id"=>113536670874,
  ...
  "created_time"=>"2015-11-27T09:17:07+0000",
  "name"=>"DJ"
 }

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    尝试使用$project,在$lookup之后添加

    {$lookup: {
              from: 'players', 
              localField: 'name', 
              foreignField: 'name',
              as: 'profile'
            }
          },
    {$project: {
               _id: '$_id', 
               author_id: 1, 
               created_time: 1, 
               name: '$profile.name'
             }
          }
    

    正如 Blacks 在 cmets 中指出的那样,输出 $loopup 更准确地说是“数组”

    "name": { 
         "$arrayElemAt": [
                  { "$map": { 
                       "input": "$profile", 
                       "as": "el", 
                       "in": "$$el.name" 
                       }},0]
             }
    

    【讨论】:

    • 嗨,谢谢,这个解决方案绝对有效。但是,hitting_stats 集合中有 10 多个字段,并且这些字段是可变的。是否有任何替代方法可以避免在投影操作中指定所有字段?
    • @newBike,$$ROOT 可以满足您的要求。
    • @newBike,这是一个相关的问题,stackoverflow.com/questions/20497499/…
    • @newBike 实际上,您的源示例并不准确,因为 $lookup 的输出字段将始终是“数组”。因此,即使结果是“一对一”,您仍然会得到一个数组作为响应,如果您希望直接重塑为顶级文档,则为您想要的每个字段制作正确的奇异投影"name": { "$arrayElemAt": [{ "$map": { "input": "$profile", "as": "el", "in": "$$el.name" }},0] } 等等。这没有什么神奇之处,因为聚合管道没有用于“循环”转换的编码结构。
    猜你喜欢
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 2012-07-19
    相关资源
    最近更新 更多