假设我了解您的数据模型,您可以使用 group 命令:
db.coll.group({
key:{session:true},
initial: {max: 0, min:100},
reduce: function(obj, prev){
if(obj.ticks > prev.max){
prev.max=obj.ticks;
}
if(obj.ticks <prev.min){
prev.min=obj.min;
}
},
finalize: function(out){
out.session_length=out.max - out.min;
}
})
示例输入:
{ "_id" : 1, "session" : 1, "ticks" : 10 }
{ "_id" : 2, "session" : 1, "ticks" : 4 }
{ "_id" : 3, "session" : 1, "ticks" : 12 }
{ "_id" : 4, "session" : 2, "ticks" : 6 }
{ "_id" : 5, "session" : 2, "ticks" : 8 }
{ "_id" : 6, "session" : 2, "ticks" : 3 }
示例输出:
[
{
"session" : 1,
"max" : 12,
"min" : 4,
"session_length" : 8
},
{
"session" : 2,
"max" : 8,
"min" : 3,
"session_length" : 5
}
]
http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Group