search

Home  >  Q&A  >  body text

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可以这么实现:

db.user.aggregate(
 {$group:{_id:"$number",total:{$sum:1}}},
 {$match:{total:1}}
);

现在改用group方法:

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;
  }
});

查不出结果,如何解决?

漂亮男人漂亮男人2887 days ago689

reply all(3)I'll reply

  • 高洛峰

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

    I tried another method, but it still didn’t work

    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;
        }
      }
    });
    

    By the way, is there any use for return in finalize?

    reply
    0
  • 高洛峰

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

    2.4 was released in 2010. The MongoDB server released at that time is no longer officially supported, so it is necessary to upgrade.

    reply
    0
  • 滿天的星座

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

    For aggregation, version 3.2 or above is recommended. It is recommended to use https://github.com/T-baby/Mon... to operate and manage mongodb. Please refer to https://t-baby.gitbooks.io/mo... . Get started in ten minutes

    reply
    0
  • Cancelreply