node.js - 使用 $unwind 获取空数组作为聚合结果
问题描述
我有一个像下面这样的文档,使用粘贴在 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);
});
解决方案
尝试在 $unwind 操作中将 preserveNullAndEmptyArrays 设置为 true。可能是因为“trip_timings”字段包含空数组而跳过了结果。$unwind 的默认行为是忽略要展开的字段不存在或为空数组的文档。更多详细信息:https ://docs.mongodb.com/manual/reference/operator/aggregation/unwind/#behaviors
推荐阅读
- spring-boot - 如何在百里香模板名称的地方发送html内容
- c - 是否可以使用 Huffman 编码压缩二进制文件?
- python - 如何返回 20 个列表数组中三个中适应度最高的个体?
- python - Python:找不到文件(pySerial)
- vb.net - 在 Visual Basic 中将项目从文本文件添加到多维数组
- scala - 按部分减少序列
- php - 使用变量 where-condition 从数据库创建 fusioncharts
- keras - 添加存在 advanced_activations 层的 dropout 层
- java - 不兼容的类型 - 在 timer.schedule run() curInterval 上找到:int required:boolean
- git - git 在 rebase 之后已经更新了远程分支后面的本地分支