suchen

Heim  >  Fragen und Antworten  >  Hauptteil

group-by - MongoDB对对聚合查询结果进行筛选

想要用java做分组查询,貌似2.4版的java驱动包不支持db.collection.aggregate语法,所以被迫改用db.collection.group()方法。
需求:要用Mongo实现该与SQL的相同作用:
select number from user group by number having count(*) = 1

使用aggregate可以这么实现:

1

2

3

4

5

<code>db.user.aggregate(

 {$group:{_id:"$number",total:{$sum:1}}},

 {$match:{total:1}}

);

</code>

现在改用group方法:

1

2

3

4

5

6

7

8

9

10

11

12

<code>db.user.group({

  key : {number:1},

  cond : {count:1},

  initial : {count: 0},

  reduce : function Reduce(doc, out) {

   out.count +=1;

  },

  finalize : function Finalize(out) {

   return out;

  }

});

</code>

查不出结果,如何解决?

漂亮男人漂亮男人2889 Tage vor696

Antworte allen(3)Ich werde antworten

  • 高洛峰

    高洛峰2017-04-25 09:06:30

    试了另一个方法,还是不行

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    <code>db.user.group({

      key : {number:1},

      cond : {},

      initial : {count: 0},

      reduce : function Reduce(doc, out) {

       out.count +=1;

      },

      finalize : function Finalize(out) {

       if(out.count==1){

            return out;

        }

      }

    });

    </code>

    话说finalize 里面的return 有任何用处吗?

    Antwort
    0
  • 高洛峰

    高洛峰2017-04-25 09:06:30

    2.4 是 2010 年发布的,那时候发布的 MongoDB server 官方都不再支持了,很有必要升级了。

    Antwort
    0
  • 滿天的星座

    滿天的星座2017-04-25 09:06:30

    聚合的话推荐3.2以上版本。推荐使用https://github.com/T-baby/Mon... 来操作和管理mongodb,可参考https://t-baby.gitbooks.io/mo... 。十分钟上手

    Antwort
    0
  • StornierenAntwort