【发布时间】:2019-05-07 07:21:39
【问题描述】:
我有两个模型 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"
}
【问题讨论】:
-
scheduleStart是来自schedules集合的字段。而您的$lookup详细信息在user_details内。所以将user_details放在$project阶段。 -
我该怎么做?
-
试试这个
{ $project: { _id: 1, name: 1, name: 1, cpf: 1, phone: 1, email: 1, birthday: 1, totalServices: 1, totalValue: { "$sum": "$user_detail.value" }, count: { $sum: 1 }, user_detail: 1 } } -
我可以只把
scheduleStart和scheduleEnd带入那个$project 中的user_detail吗?
标签: javascript mongodb mongoose aggregation-framework