$ lookup中的$ project mongodb [英] $project in $lookup mongodb
本文介绍了$ lookup中的$ project mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个查询,它使用 $ lookup 来加入"两个模型,此后,我使用 $ project 选择olny我需要的字段,但是我的$ project带来了一大堆对象(user_detail
),其中包含我需要的更多数据.我只需要结果的两个字段(scheduleStart
和scheduleEnd
).
I have a query, that use $lookup to "join" two models, after this i use $project to select olny the fields that i need, but my $project brings an arrray of objects (user_detail
) that contains more data that i need. I want only two fields (scheduleStart
and scheduleEnd
) of my result.
我的查询:
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: "csantosgrossi@gmail.com"
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: "csantosgrossi@gmail.com"
id: "5bfed8bd70de7a383855f09e"
name: "Chris Santos G"
phone: "11969109995"
...
我该如何处理查询?
推荐答案
您可以使用 $project
You can use $lookup
3.6 syntax to $project
the fields inside the $lookup
pipeline
User.aggregate([
{ "$lookup": {
"from": "schedules",
"let": { "id": "$_id.phone" },
"pipeline": [
{ "$match": { "$expr": { "$eq": ["$customer.phone", "$$id"] }}},
{ "$project": { "scheduleStart": 1, "scheduleEnd": 1 }}
],
"as": "user_detail"
}}
])
这篇关于$ lookup中的$ project mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文