$ lookup を使用して2つのモデルを「結合」するクエリがあります。この後、 $ project を使用して必要なフィールドを選択しますが、$ projectによってオブジェクトの配列(user_detail
)必要なデータがさらに含まれています。結果の2つのフィールド(scheduleStart
およびscheduleEnd
)のみが必要です。
私のクエリ:
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" },
count: {
$sum: 1
},
user_detail: 1
}
},
クエリの結果:
count: 1
totalServices: 0
totalValue: 73
user_detail: Array(2)
0:
...
paymentMethod: 0
paymentValue: "0"
scheduleDate: "2018-10-02"
scheduleEnd: "2018-10-02 08:40"
scheduleStart: "2018-10-02 08:20"
status: 3
store: "5b16cceb56a44e2f6cd0324b"
updated: "2018-11-27T13:30:21.116Z"
1:
...
paymentMethod: 0
paymentValue: "0"
scheduleDate: "2018-11-27"
scheduleEnd: "2018-11-27 00:13"
scheduleStart: "2018-11-27 00:03"
status: 2
store: "5b16cceb56a44e2f6cd0324b"
updated: "2018-11-27T19:33:39.498Z"
_id:
birthday: "1992-03-06"
email: "[email protected]"
id: "5bfed8bd70de7a383855f09e"
name: "Chris Santos G"
phone: "11969109995"
...
必要な結果:
count: 1
totalServices: 0
totalValue: 73
user_detail: Array(2)
0:
scheduleEnd: "2018-10-02 08:40"
scheduleStart: "2018-10-02 08:20"
1:
scheduleEnd: "2018-11-27 00:13"
scheduleStart: "2018-11-27 00:03"
_id:
birthday: "1992-03-06"
email: "[email protected]"
id: "5bfed8bd70de7a383855f09e"
name: "Chris Santos G"
phone: "11969109995"
...
クエリでこれを行うにはどうすればよいですか?
Mongo <3.6のバージョンでは、このクエリはあなたのために働くはずです:
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" },
count: {
$sum: 1
},
user_detail: {
scheduleEnd: 1,
scheduleStart: 1,
}
}
},