【问题标题】:Mongodb aggregate field total incorrectMongodb聚合字段总数不正确
【发布时间】:2015-11-22 08:31:00
【问题描述】:

基本上,我试图找到所有与文本搜索不匹配的文档,然后对文档字段进行一些数学运算以返回总数。这是我试图做的,但它不起作用。

db.my_collection.aggregate(
  [
    { $match: { $text: { $search: "annual one-time One_time monthly quarterly" } } },
    { $project: { _id: 0, score: { $meta: "textScore" } } },
    { $group: { _id: {score: "$score"},  
       totalAmount: { $sum: { $divide: [ { $add: [ "$amount_in_cents" ] }, 100 ] } },       
       count: { $sum: 1 }
    } }

  ]);

这是我得到的。

[
{
    "_id" : {
        "score" : 0.7500000000000000
    },
    "totalAmount" : 0,
    "count" : 1.0000000000000000
},
{
    "_id" : {
        "score" : 1.0000000000000000
    },
    "totalAmount" : 0,
    "count" : 57.0000000000000000
},
{
    "_id" : {
        "score" : 1.5000000000000000
    },
    "totalAmount" : 0,
    "count" : 7.0000000000000000
}
]

如何使每个分数分组的总金额准确无误,以及如何仅获取那些没有任何搜索字词的搜索的分数分组?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您在执行$project 时删除了内容,这就是为什么当您稍后去引用一个因此不再存在的字段时它不会显示的原因。

    这里要记住聚合的事情是它是一个“管道”,其中最接近的类比是管道| 运算符,它将可用于您的外壳或命令提示符,具体取决于您的操作系统类型使用。

    用一个常见的 Unix 习语来思考:

    ps -ef | grep "mongo" | tee "mongoproc".txt
    

    如果有一个ps 命令,它的输出被“传送”到grep 命令,后者又“过滤”内容,因此再次“传送”的输出在发送到时只包含匹配的值tee,它还将输出重定向到指定文件。

    聚合框架发生的事情完全相同,因为您只能在下一个阶段“进入”前一个阶段“出来”的内容。

    所以$project 在聚合管道中的工作方式与在基本查询投影中的工作方式略有不同。在这里,您必须“明确”指定您想要的所有字段,以便将这些字段输出并在后续阶段中使用:

       db.my_collection.aggregate(
          [
            { $match: { 
                $text: { 
                    $search: "annual one-time One_time monthly quarterly"
                } 
            }},
            { $project: { 
                _id: 0, 
                amount_in_cents: 1,
                score: { $meta: "textScore" } 
            }},
            { $group: { 
                _id: { score: "$score"},  
               totalAmount: { $sum: { $divide: [ { $add: [ "$amount_in_cents" ] }, 100 ] } },       
               count: { $sum: 1 }
            }}
        ]);
    

    【讨论】:

    • 谢谢,这回答了我的问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多