【问题标题】:How to aggregate new document from Mongodb如何从 Mongodb 聚合新文档
【发布时间】:2020-08-09 18:18:06
【问题描述】:

我有一个显示收入的 MonoDB。它有_id、姓名和收入文件。我想编写一个查询返回名称和一个名为 AverageIncome 的新文档,该文档在收入

db.collection.aggregrate([{income:{$exists:true}}, {$project:{income:1, Averageincome: {$cond:{if;{$gte:{$'income', 40000]}, then: true, else:false}}}}])

我得到了一个输出,但它远远超出了我的需要。还有其他想法吗?

【问题讨论】:

    标签: mongodb aggregation-framework


    【解决方案1】:

    您需要在$match 阶段中​​定义您的第一步。由于$gte 运算符返回true|false,因此您无需添加$cond 运算符。

    试试这个:

    db.collection.aggregate([
      {
        $match: {
          income: {
            $exists: true
          }
        }
      },
      {
        $project: {
          name:1,
          income: 1,
          Averageincome: {
            $gte: [
              "$income",
              40000
            ]
          }
        }
      }
    ])
    

    MongoPlayground

    【讨论】:

    • 嗨,该代码有效,但它不返回获得平均收入的人的姓名。我已经试着弄清楚了,我应该使用 find 吗??
    • @Peadar08 再检查一遍,我们只需要包含name 字段即可。
    • 我已经尝试过了,但出现错误 db.docs.find({income:{$exists:true}}, {_id:0, name:1, level:1}, {AveIncome :{$cond:{if:{$gte:[$'income', 40000]}}, then: true, else: false }}) 错误是 E QUERY [js] 未捕获的异常:SyntaxError: missing ] after element列表:
    • @Peadar08 你不能用.find方法运行do it,它应该是.aggregate
    • 谢谢。我刚刚发布了那个。我要使用聚合,但不明白为什么以下方法不起作用 db.docs.aggregate({[$match:{income:{$exists:true}}, {_id:0, name:1}, {AveIncome :{$cond:{if:{$income:{$gt: 40000}}}, then: true, else: false }}}])
    猜你喜欢
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2017-03-18
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 2013-09-18
    相关资源
    最近更新 更多