javascript - Mongoose:$lookup 后的 $project 不显示字段
问题描述
我有两个模型user.js和schedule.js并且我有一个查询(聚合),我需要使用$lookup来“加入”这些模型。在 $lookup 之后,我使用了一个$project来选择我想在查询结果中显示的字段,但这些字段scheduleStart
并scheduleEnd
没有显示在我的结果中。
User.js(模型)
name: {
type: String,
required: true
},
firstName: {
String
},
lastName: {
String
},
storeKey: {
type: String,
required: true
},
avatar: String,
birthday: String,
phone: {
type: String
},
doc: String,
email: {
type: String
},...
Schedule.js(模型)
service: {
id: {
type: String
},
name: {
type: String,
required: true
},
filters: [String]
},
info: {
channel: {
type: String,
required: true,
default: 'app'
},
id: String,
name: String
},
scheduleDate: {
type: String,
required: true
},
scheduleStart: {
type: String,
required: true
},
scheduleEnd: {
type: String,
required: true
},
我的查询
User.aggregate([{
$match: {
storeKey: req.body.store,
}
},
{
$group: {
_id: {
id: "$_id",
name: "$name",
cpf: "$cpf",
phone: "$phone",
email: "$email",
birthday: "$birthday",
lastName: "$lastname"
},
totalServices: {
$sum: "$services"
},
}
},
{
$lookup: {
from: "schedules",
localField: "_id.phone",
foreignField: "customer.phone",
as: "user_detail"
}
},
{
$project: {
_id: 1,
name: 1,
name: 1,
cpf: 1,
phone: 1,
email: 1,
birthday: 1,
totalServices: 1,
totalValue: { "$sum": "$user_detail.value" },
scheduleStart: 1,
scheduleEnd: 1,
count: {
$sum: 1
}
}
}
])...
我的查询结果:
count: 1
totalServices: 89
totalValue: 2374
_id:{
birthday: "1964-03-18",
cpf: "319335828",
email: "jdoe@gmail.com.br",
id: "5b1b1dcce1ab2a8eb580f",
name: "Jonh Doe",
phone: "11996370565"
}
解决方案
您可以将以下$project
阶段与$arrayElemAt
聚合一起使用
{ '$project': {
'_id': 1,
'name': 1,
'cpf': 1,
'phone': 1,
'email': 1,
'birthday': 1,
'totalServices': 1,
'totalValue': { '$sum': '$user_detail.value' },
'scheduleStart': { '$arrayElemAt': ['$user_detail.scheduleStart', 0] },
'scheduleEnd': { '$arrayElemAt': ['$user_detail.scheduleEnd', 0] },
'count': { '$sum': 1 }
}}
推荐阅读
- javascript - 从数组向对象添加值,并且在数组用完时不会变为未定义
- excel - 如何在 VBA IE 自动化中相对单击复选框(通过提供来自 excel 单元格的数据)?
- matlab - 如何将 TF 训练的网络导出到 h5 文件
- python - PyQt5 QSlider 根据滑块移动的方向关闭一个
- mysql - 如何在 MySQL 中创建一个查看两个表的 Select 语句
- linux - 运行 vagrant up 时显示错误消息
- java - Java 11 jar 命令是否支持 classpath 参数?
- django - 当 pk 包含“。”时,ViewSet 检索的 URL 问题
- python - 无法使用 plt.imshow 显示图片
- jquery - 如何使 Pardot 上的 Jq 脚本更短更高效