【问题标题】:How to compare string feild value in aggregation mongodb如何比较聚合mongodb中的字符串字段值
【发布时间】: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]}
}

compass image link

示例文档 我有多个这样的文件

{
  "_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]} 看起来你混合了聚合运算符$eq 和查询运算符$eq
  • 我使用了 {$cond:[{$eq: ['$answers.SEC.text','A']}, 1, 0]}。但它总是返回 false,没有匹配,导致 $cond 返回 0。我不知道为什么。
  • 请提供相同的样本输入文件。
  • 我在我的问题中提供了示例文档
  • 样本数据与您的聚合管道完全不匹配。期望的结果是什么?

标签: javascript node.js mongodb mongodb-compass nosql-aggregation


【解决方案1】:

试试这个:

db.collection.aggregate([
   {
      $project: {
         'answers.Urban_City.text': 1,
         SEC_A: {
            $map: {
               input: "$answers",
               in: { $cond: [{ $eq: ['$$this.SEC.text', 'A'] }, 1, 0] }
            }
         }
      }
   }
])

如果您提供所需的样本输出,则更改会更高以获得适当的答案。

【讨论】:

  • 您的答案显示错误“管道阶段规范对象必须包含一个字段”。
  • 我已经编辑了我的问题,请您参考
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-03
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多