【问题标题】:How to group query with multiple $cond?如何使用多个 $cond 对查询进行分组?
【发布时间】:2013-12-30 09:44:12
【问题描述】:

我想像下面这样查询,但这只包含一个$cond

两个$cond如何查询?

collection.aggregate(
    { 
        $match : { 
            '_id' : {$in:ids}
        } 
    },
    {
        $group: {
            _id: '$someField',
            ...
            count: {$sum: { $cond: [ { $eq: [ "$otherField", false] } , 1, 0 ] }}
        }
    },
    function(err, result){
        ...
    }
);

【问题讨论】:

  • 如果它们完全不同,那么您需要向$group 添加一个全新的字段,这基本上是您的count 字段的副本,但名称当然不同
  • 我要检查 $anotherField, "value" 和 $otherField, false
  • 但是我假设您还想要不满足该条款的文档,否则您可以将其放入匹配项中
  • 是的,我想获得其他不满足该条款的文件。所以条件必须在 sum 子句中..
  • 我不完全清楚你想要做什么,但 StackOverflow 上还有一些其他示例,nested $cond(类似于 case 语句)或使用 multiple $cond。我认为您所追求的是嵌套的$cond,您可以通过在$otherField 不为假的表达式中添加另一个$cond 比较来有条件地对$anotherField 进行匹配。

标签: mongodb aggregation-framework


【解决方案1】:

您想在 {$cond:[]} 中使用复合表达式 - 类似于:

collection.aggregate(
    { 
        $match : { 
            '_id' : {$in:ids}
        } 
    },
    {
        $group: {
            _id: '$someField',
            ...
            count: {$sum: { $cond: [ {$and : [ { $eq: [ "$otherField", false] },
                                               { $eq: [ "$anotherField","value"] }
                                     ] },
                                     1,
                                     0 ] }}
        }
    },
    function(err, result){
        ...
    }
);

$and operator 记录在这里:http://docs.mongodb.org/manual/reference/operator/aggregation/#boolean-operators

【讨论】:

  • 我们可以在聚合管道中使用 function() 吗?
  • 不确定您的意思,但在管道中,所有内容都必须解析为管道语法,换句话说,您可以使用函数将某些内容扩展为正确的语法,但不要在运行时调用它。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-17
  • 2019-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多