如何在MongoDb中执行不区分大小写的聚合分组?

时间:2017-09-08 19:49:19

标签: mongodb aggregation-framework

假设我想通过<?php if(($_SESSION['is_accepted']) == false): ?> <div class="row" style="margin-top: 40px;margin-bottom: 40px"> <div class="form-horizontal"> <div class="col-sm-4 col-sm-offset-5"> <button class="btn btn-primary" onclick="window.location='<?php echo base_url('saveUpdate'); ?>'">Aceitar contrato</button> </div> </div> </div> <?php endif;?> 字段按MongoDb中的文档进行汇总和分组。

运行以下命令(默认情况下区分大小写):

Description

我的样本数据给了我1000个结果,这很好。

但现在我希望运行 不区分大小写的 查询(使用db['Products'].aggregate( { $group: { _id: { 'Description': "$Description" }, count: { $sum: 1 }, docs: { $push: "$_id" } }}, { $match: { count: { $gt : 1 } }} ); )会给我小于或等于1000的结果:

$toLower

但相反,我获得了超过1000个结果。那可能不对,可以吗?更常见的条目应该组合在一起,以产生更少的总分组...我认为。

那么可能我的聚合查询错了!这让我想到了我的问题:

如何执行MongoDb中不区分大小写的聚合分组?

1 个答案:

答案 0 :(得分:3)

你接近不区分大小写的分组是正确的,所以也许你的观察不是吗? ;)

试试这个例子:

// insert two documents
db.getCollection('test').insertOne({"name" : "Test"}) // uppercase 'T'
db.getCollection('test').insertOne({"name" : "test"}) // lowercase 't'

// perform the grouping
db.getCollection('test').aggregate({ $group: { "_id": { $toLower: "$name" }, "count": { $sum: 1 } } }) // case insensitive
db.getCollection('test').aggregate({ $group: { "_id": "$name", "count": { $sum: 1 } } }) // case sensitive

你可能在某个地方有拼写错误?

documentation也说明了

  

$ toLower只对ASCII字符串有明确定义的行为。

也许这就是你在这里咬什么?

相关问题