2015-12-14 62 views
3

我有一个在mongoDB中的集合,每天都有一个带有采样数据的文档被添加到它。我想观察字段的变化。mongolDB聚合分组相似的文件彼此相邻

我想使用MongoDB的聚集将类似的项目彼此相邻的第一:

+--+-------------------------+ 
|id|field    | date | 
+--+-------------------------+ 
| 1|hello    | date1| 
+--+-------------------------+ 
| 2|foobar   | date2| \_ Condense these into one row with date2 
+--+-------------------------+/
| 3|foobar   | date3| 
+--+-------------------------+ 
| 4|hello    | date4| 
+--+-------------------------+ 
| 5|world    | date5| \__ Condense these into a row with date5 
+--+-------------------------+/
| 6|world    | date6| 
+--+-------------------------+ 
| 7|puppies   | date7| 
+--+-------------------------+ 
| 8|kittens   | date8| \__ Condense these into a row with date8 
+--+-------------------------+/
| 9|kittens   | date9| 
+--+-------------------------+ 

是否有可能创造该问题的MongoDB的聚集?

这里是回答类似的问题在MySQL: Grouping similar rows next to each other in MySQL

样本数据

数据已按日期排序。

这些文件:

{ "_id" : "566ee064d56d02e854df756e", "date" : "2015-12-14T15:29:40.432Z", "score" : 59 }, 
{ "_id" : "566a8c70520d55771f2e9871", "date" : "2015-12-11T08:42:23.880Z", "score" : 60 }, 
{ "_id" : "566932f5572bd1720db7a4ef", "date" : "2015-12-10T08:08:21.514Z", "score" : 60 }, 
{ "_id" : "5667e652c021206f34e2c9e4", "date" : "2015-12-09T08:29:06.696Z", "score" : 60 }, 
{ "_id" : "5666a468cc45e9d9a82b81c9", "date" : "2015-12-08T09:35:35.837Z", "score" : 61 }, 
{ "_id" : "56653fe099799049b66dab97", "date" : "2015-12-07T08:14:24.494Z", "score" : 60 }, 
{ "_id" : "5663f6b3b7d0b00b74d9fdf9", "date" : "2015-12-06T08:49:55.299Z", "score" : 60 }, 
{ "_id" : "56629fb56099dfe31b0c72be", "date" : "2015-12-05T08:26:29.510Z", "score" : 60 } 

应群:

{ "_id" : "566ee064d56d02e854df756e", "date" : "2015-12-14T15:29:40.432Z", "score" : 59 } 
{ "_id" : "566a8c70520d55771f2e9871", "date" : "2015-12-11T08:42:23.880Z", "score" : 60 } 
{ "_id" : "5666a468cc45e9d9a82b81c9", "date" : "2015-12-08T09:35:35.837Z", "score" : 61 } 
{ "_id" : "56653fe099799049b66dab97", "date" : "2015-12-07T08:14:24.494Z", "score" : 60 } 
+0

两行如何定义为*彼此相邻*? – BatScream

+0

@BatScream - 我添加了示例数据。它们按日期相邻定义。 – Homa

+0

记录是否按日期按降序排序,然后再进行分组? – BatScream

回答

1

如果你不使用aggregation框架坚持,这可以通过循环光标,比较每个文件进行到前一个:

var cursor = db.test.find().sort({date:-1}).toArray(); 
var result = []; 
result.push(cursor[0]); //first document must be saved 
for(var i = 1; i < cursor.length; i++) { 
    if (cursor[i].score != cursor[i-1].score) { 
     result.push(cursor[i]); 
    } 
} 

结果:

[ 
    { 
     "_id" : "566ee064d56d02e854df756e", 
     "date" : "2015-12-14T15:29:40.432Z", 
     "score" : 59 
    }, 
    { 
     "_id" : "566a8c70520d55771f2e9871", 
     "date" : "2015-12-11T08:42:23.880Z", 
     "score" : 60 
    }, 
    { 
     "_id" : "5666a468cc45e9d9a82b81c9", 
     "date" : "2015-12-08T09:35:35.837Z", 
     "score" : 61 
    }, 
    { 
     "_id" : "56653fe099799049b66dab97", 
     "date" : "2015-12-07T08:14:24.494Z", 
     "score" : 60 
    } 
]