【问题标题】:Getting empty array as aggregate result with $unwind使用 $unwind 获取空数组作为聚合结果
【发布时间】:2019-02-19 23:33:51
【问题描述】:

我有一个类似下面的文档,使用粘贴在 json 数据之后的 mongoose 应用了聚合查询。在这里,我尝试使用子收集时间的字段。查询结果为空数组,请帮忙查找查询错误。查询适用于删除 $unwind 和相关的 $project 字段

{  
   "_id":"5b9cbeff67ea7bc00c9917a5",
   "route_index":0,
   "route_name":"NH85", 
   "access_type":"public",
   "type":"bus", 
   "duration_days":null,
   "duration_hours":0.23,
   "created_on":"2018-09-15T07:50:17.211Z",
   "title":"Rx100",
   "description":"Ls",
   "timings":[  
      {  
         "departure":"08:00",
         "destination":"08:23",
         "_id":"5b9cbeff67ea7bc00c9917a3",
         "trackings":[  

         ]
      },
      {  
         "departure":"10:00",
         "destination":"10:23",
         "_id":"5b9cbeff67ea7bc00c9917a2",
         "trackings":[  

         ]
      }
   ],
   "created_uid":"5b8f1a9db83bc9bf3d89dcc5", 
   "__v":0
}

我尝试过的查询在这里:

Transport.aggregate([
        { $unwind: "$timings" } 
        {
            $project: {
                title: 1,  
                "trip_timings": "$timings"
            }
        }, 
        { $skip: ((perPage * page) - perPage) },
        { $limit: perPage }
    ], function (err, data) {
        if (err) {
            res.json(err);
        }
        res.json(data);
    });

【问题讨论】:

  • 您能否也发布样本收集以进行计时
  • 尝试删除 $skip 和 $limit。可能他们只是跳过了结果。
  • Anthony,timings 是我分享的 json 的子集合,你可以在里面看到。

标签: node.js mongodb mongoose


【解决方案1】:

尝试在 $unwind 操作中将 preserveNullAndEmptyArrays 设置为 true。可能是因为“trip_timings”字段包含空数组而跳过了结果。 $unwind 的默认行为是忽略要展开的字段不存在或为空数组的文档。更多细节在这里:https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/#behaviors

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-03
    • 2016-04-08
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多