MongoDB查询语句

1、group by having 结果集存储

 

var a=db.Topic.aggregate({$group:{_id:"$Tid",count:{$sum:1}}},{$match:{count:{"$gt":1}}});
while(a.hasNext()) db.ea.insert(a.next());

2、dynamically where

 var a=new Array();
 for(var i=0;i<db.ea.count();i++)a.push(db.ea.find()[i].Tid);
 db.Topic.find({Tid:{$in:a}});

3、删除重复数据

根据上一段语句可以得到所有重复数据

插入一个新表

var b=db.Topic.find({Tid:{$in:a}});
while(b.hasNext()) db.xx.insert(b.next());

group by 找到min UpdateTime 就是需要删除的对象

var c=db.xx.aggregate({$group:{_id:"$Tid",updateTime:{$min:"UpdateTime"}}});
while(c.hasNext()) db.del.insert(c.next());
var d=new Array();
for(var i=0;i<db.del.count();i++)d.push(db.del.find()[i]._id);
db.Topic.remove({Tid:{$in:d}});

//foreach

db.User.find().forEach(function(x){db.User.update({Uid:x.Uid},{$set:{CreateTime:0,UpdateTime:0}});})

//group by

db.Topic.aggregate([{ $project: { day: { $dateToString: { format: ‘%Y-%m-%d’, date: { $add: [new Date(0), { $multiply:[{$sum: [‘$UpdateTime’, 28000] },1000]}]}}}}}, { $group: { _id: ‘$day’, number: { $sum: 1 } } }, { $sort: { _id: -1 } }]);

 

4、直接去重复数据

db.zbgg.aggregate([{$group: { _id: {title: ‘$title’},count: {$sum: 1},dups: {$addToSet: ‘$_id’}}},{$match: {count: {$gt: 1}}}]).forEach(function(doc){doc.dups.shift();db.zbgg.remove({_id: {$in: doc.dups}});})

发表评论