group-by - MongoDB对对聚合查询结果进行筛选
漂亮男人
漂亮男人 2017-04-25 09:04:30
0
3
645

想要用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;
  }
});

查不出结果,如何解决?

漂亮男人
漂亮男人

reply all(3)
小葫芦

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?

小葫芦

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

滿天的星座

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template