在Spring-data-mongodb中使用$ cond运算符 [英] Using $cond operator with Spring-data-mongodb

查看:783
本文介绍了在Spring-data-mongodb中使用$ cond运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望汇总以下数据

{
   "user": "user1",
   "error": true 
}
{
   "user": "user2",
   "error": false
}
{
   "user": "user1",
   "error": false
}

进入

{
     "_id": "user1",
     "errorCount": 1,
     "totalCount": 2
},
{
     "_id": "user2",
     "errorCount": 0,
     "totalCount": 1
}

使用$ cond运算符,可以使用以下方法实现:

With $cond operator, this can be achieved using:

$group: {
    _id: "$user",
    errorCount : { "$sum" : {"$cond" : ["$error", 1, 0]}},
    totalCount : { "$sum" : 1 }
}

但是,由于我正在使用不支持$ cond的Spring-data-mongodb(从1.3.4-RELEASE版本开始),所以我无法做到这一点.

However, since I am using Spring-data-mongodb which does not yet support $cond (as of 1.3.4-RELEASE), I couldn't do this.

是否可以在没有$ cond的情况下进行相同的聚合?

Is there a way to do the same aggregation without $cond?

推荐答案

即使Spring数据中还没有功能性接口",您也不受此约束. (顺便说一句,提高JIRA)

You are not bound to this even if there is no "functional interface" in Spring data yet. (BTW, raise a JIRA)

只需获取本机表单并在管道中使用BasicDBObject类型.因此,原则上:

Just get the native form and use BasicDBObject types in the pipeline. So in principle:

    DBCollection myCollection = mongoOperation.getCollection("collection");

    <result cast> = myCollection.aggregate(<pipeline here>);

Spring数据为您提供了抽象,但它没有禁止使用 native 驱动程序功能.正如我上面演示的那样,它实际上使您访问者可以使用它们.

Spring data gives you abstractions, but it does not prohibit the use of the native driver functions. It actually gives you accessors to use them, as I demonstrated above.

这篇关于在Spring-data-mongodb中使用$ cond运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆