【发布时间】:2022-01-13 07:20:30
【问题描述】:
在下图中,我正在使用 $project 聚合。我需要使用 $cond 比较 text 字段是否等于“A”。如果此布尔条件为真,则应返回 1,否则返回 0。但它显示 必须正确格式化舞台。
{
'answers.Urban_City.text': 1,
SEC_A: {$cond:['answers.SEC.text':['$eq','A'], 1, 0]}
}
示例文档 我有多个这样的文件
{
"_id": {
"$oid": "61dea2c1169cd059e2d1a06e"
},
"metaKey": {
"projectId": 7,
"sectionId": 5,
"userId": 5,
"simpleSurveyResponseCode": "58836213476714"
},
"answers": [
{
"Urban_City": {
"text": "Karachi",
"value": "72"
}
},
{
"SEC": {
"text": "A",
"value": "1"
}
}
],
"__v": 0
}
我想要这样的东西
db.Sentiments.aggregate(
{ $project: {
_id: 0,
Company: 1,
PosSentiment: {$cond: [{$gt: ['$Sentiment', 0]}, '$Sentiment', 0]},
NegSentiment: {$cond: [{$lt: ['$Sentiment', 0]}, '$Sentiment', 0]}
}},
{ $group: {
_id: "$Company",
SumPosSentiment: {$sum: '$PosSentiment'},
SumNegSentiment: {$sum: '$NegSentiment'}
}});
但在 Sentiment 的地方,我有 SEC,它是嵌入式数组,包含示例文档中提到的两个字段(String)。如果这个问题得到解决,我会陷入 $project 聚合中 $group 对我来说很容易。
【问题讨论】:
-
我使用了 {$cond:[{$eq: ['$answers.SEC.text','A']}, 1, 0]}。但它总是返回 false,没有匹配,导致 $cond 返回 0。我不知道为什么。
-
请提供相同的样本输入文件。
-
我在我的问题中提供了示例文档
-
样本数据与您的聚合管道完全不匹配。期望的结果是什么?
标签: javascript node.js mongodb mongodb-compass nosql-aggregation