【问题标题】:Filter an aggregate by string length [duplicate]按字符串长度过滤聚合[重复]
【发布时间】:2018-04-26 11:49:42
【问题描述】:

我执行了以下查询:

db.Indiv2.aggregate(
{$unwind: '$conso'},
{$group: {_id: {conso:'$conso.nom_commercial', region:"$region"}, sum: 
{$sum: 1}}},
{$sort : {sum : -1}},
{$group: {
_id: "$_id.region",
"conso": {
    $first: "$_id.conso"
},
"sum": {
    $first: "$sum"
},
}},
{$sort : {_id : 1}}
);

按以下格式返回按地区消耗最多的食物:

    {
        "_id" : {
            "conso" : "x",
            "region" : 1
        },
        "sum" : 73226.0
    },
    {
        "_id" : {
            "conso" : "x",
            "region" : 8
        },
        "sum" : 25683.0
    },
    {
        "_id" : {
            "conso" : "grandlait demi �cr�m� uht",
            "region" : 1
        },
        "sum" : 251.0
    }

但是,很多食物没有名字。这些项目被命名为“x”(上面的例子)。我想过滤我的查询以排除此类项目。我正在寻找一个等效的过滤器,它可以过滤长度小于 2 个字符的字符串或过滤字符串“x”。

【问题讨论】:

  • 您能否使用edit 链接显示来自Indiv2 集合的一些示例文档以及您的预期输出?

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

这里有一个$redact 运算符可能会有所帮助:

试试:

db.collection.aggregate([
    //previous aggregations
    {
        "$redact": {
            "$cond": [
                { "$gt": [ { "$strLenCP": "$_id.conso" }, 2] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

【讨论】:

    【解决方案2】:

    您可以捕获 conso 长度并过滤。鉴于上述 or 条件,我们最终得到:

    // previous pipeline here, then:
    {$addFields: {slen: {$strLenBytes: "$_id.conso"}}}
    ,{$match: {$or: [ {"_id.conso": {$ne: "x"}}, {slen: {$gt: 1}} ] }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      • 2012-05-22
      相关资源
      最近更新 更多