node.js - MongoDB & Node.js - 如何用 $eq 和 $cond 对字段求和,其中表达式是对象数组
问题描述
我们有这个代码。请检查我们在
$project:
sumVentaWp
sumVentaMail
sumAlquilerWp
sumAlquilerMail
主要目标是得到一个条件的总和,问题是它dwellingDetail
是dwellingDetail.publicationType
对象数组,我认为我们不能将它与“Venta”进行比较(这就是它总是返回 0 的原因)。
$eq: ["$dwellingDetail.publicationType", "Venta"]
有没有办法检查住宅详细信息中的特定对象?
{
$lookup: {
localField: '_id',
from: 'inquiries', //the collection name, (bad)before i had Phrase as the model
foreignField: 'agencyId',
as: 'inquiries'
},
},
{
$lookup: {
localField: 'inquiries.dwellingId',
from: 'dwelling', //the collection name, (bad)before i had Phrase as the model
foreignField: '_id',
as: 'dwellingDetail'
},
},
{
$match: {
'deleted': false,
}
},
{ $sort: { name: 1 } },
{
$project: {
agencyname: '$name',
agencyId: '$_id',
sumVentaWp: {
$sum: { $cond: { if: { $eq: ["$dwellingDetail.publicationType", "Venta"] }, then: 1, else: 0 } }
},
sumVentaMail: {
$sum: { $cond: [{ $eq: ['$dwellingDetail.publicationType', "Venta"] }, 1, 0] }
},
sumAlquilerWp: {
$sum: { $cond: [{ $eq: ['$dwellingDetail.publicationType', "Alquiler"] }, 1, 0] }
},
sumAlquilerMail: {
$sum: { $cond: [{ $eq: ['$dwellingDetail.publicationType', "Alquiler"] }, 1, 0] }
},
pubType: '$dwellingDetail.publicationType',
whatsappcounter: {
$sum: '$inquiries.whatsappcounter'
},
mailcounter: { $sum: '$inquiries.mailcounter' },
'detail._id': '0'
}
}
]).exec();```
解决方案
您不能与之比较['Venta']
,'Venta'
而是可以使用$in:
{
$project: {
agencyname: '$name',
agencyId: '$_id',
sumVentaWp: {
$sum: { $cond: [{ $in: [ "Venta","$dwellingDetail.publicationType"] }, then: 1, else: 0 ] }
},
sumVentaMail: {
$sum: { $cond: [{ $in: [ "Venta", '$dwellingDetail.publicationType'] }, 1, 0] }
},
sumAlquilerWp: {
$sum: { $cond: [{ $in: ["Alquiler",'$dwellingDetail.publicationType'] }, 1, 0] }
},
sumAlquilerMail: {
$sum: { $cond: [{ $in: [ "Alquiler",'$dwellingDetail.publicationType'] }, 1, 0] }
},
pubType: '$dwellingDetail.publicationType',
whatsappcounter: {
$sum: '$inquiries.whatsappcounter'
},
mailcounter: { $sum: '$inquiries.mailcounter' },
'detail._id': '0'
}
}
注意:以防万一您有多个条件要检查,您可以尝试使用$switch。
推荐阅读
- dictionary - 如何在 main.ml 文件中使用此字典(创建字典、添加元素、删除 ....)?
- phpstorm - PhpStorm 从代码选择生成模板
- python - 将函数分配给类而不调用此函数?
- javascript - 如何根据我在 javascript 中的输入设置显示不同内容的弹出窗口
- c# - 将 dataType[] 替换为 List
- html - 有没有办法在影子 dom 中选择实际的第一个孩子?
- java - Spring Data JPA - 是否可以在将实体持久保存在存储库中之前使用主体更新实体?
- android - Xamarin Android - ContentPage.Title 总是大写
- javascript - React-Redux 中状态更改时如何关闭模态对话框?
- python - 如何从列表中随机提取并将其放入 Python 中的另一个列表中?