I'm using Mongoose /Node.js How can I find the distinct msg and its item's all attribute? And also the count of msg occurs?
example:
var LogSchema = new Schema({
msg: {
type: String
},
status: {
type: String,
default: '200'
}});
there are items in db:
{_id:'1',msg:'1',status:1},
{_id:'2',msg:'1',status:2},
{_id:'3',msg:'1',status:1},
{_id:'4',msg:'1',status:2},
{_id:'5',msg:'2',status:2},
{_id:'6',msg:'2',status:2},
{_id:'7',msg:'2',status:2},
The result I need is:
{_id:'1',msg:'1',status:1,count:4},
{_id:'5',msg:'2',status:1,count:3}
Maybe I didn't describe my question clearly.I displayed the result because {_id:'1',msg:1,status:1} occured first in the msg:1 collections.Also {_id:'5',msg:1,status:1} occured first in the msg:2 collections.All I need is to find out all the same 'msg' and the first one of them.
So,how should I write js code ?
You can use the aggregation tools of MongoDB.
LogModel.aggregate(
[
{
$group:
{
_id: '$msg',
firstId: { $first: '$_id' },
count: { $sum: 1 }
}
}
]
)
Last,I find all of them and handle them with js code. Like this:
Log.find({},needShow.join(' ')).exec(function(err, logs) {
if (!err) {
//To find out the distinct one and the count of repeat
var lastTime = new Date();
logs.sort(function(pre,cur){
return pre.time-cur.time;
})
var need = [];
for (var i = 0; i < logs.length - 1; i++) {
var item = logs[i].toObject();
item.count = 1;
item.ids = [item._id];
var j = 0;
for (; j < need.length; j++) {
if (item.msg == need[j].msg) {
need[j].ids.push(logs[j]._id);
need[j].count++;
break;
}
}
if (j == need.length) {
need.push(item);
}
}
} else {
console.log(err);
}
})