我有两个模型 user.js 和 schedule.js ,并且我有一个查询(汇总),我需要使用$lookup来“加入”这些模型。在$ lookup之后,我使用$project来选择要在查询结果中显示的字段,但是字段python -m pip install --upgrade pip
和scheduleStart
不在我的查询中结果。
User.js(模型)
scheduleEnd
Schedule.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
},...
我的查询
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
}
}
}
])...
答案 0 :(得分:1)
您可以在$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 }
}}