我試圖查詢mongoDB來獲取數據聚合(組,匹配,最後)。這裏是我的文檔:mongodb不同的groupby多個鍵
{
"_id" : 1,
"from" : "a",
"to" : "b",
"message" : "a to b",
"createdAt" : ISODate("2015-06-06T16:42:32.789Z"),
"updatedAt" : ISODate("2015-06-06T16:42:32.789Z")
}
{
"_id" : 2,
"from" : "a",
"to" : "c",
"message" : "a to c",
"createdAt" : ISODate("2015-06-06T16:43:32.789Z"),
"updatedAt" : ISODate("2015-06-06T16:43:32.789Z")
}
{
"_id" : 3,
"from" : "b",
"to" : "c",
"message" : "b to c",
"createdAt" : ISODate("2015-06-06T16:44:32.789Z"),
"updatedAt" : ISODate("2015-06-06T16:44:32.789Z")
}
{
"_id" : 4,
"from" : "a",
"to" : "c",
"message" : "a to c2",
"createdAt" : ISODate("2015-06-06T16:45:32.789Z"),
"updatedAt" : ISODate("2015-06-06T16:45:32.789Z")
}
{
"_id" : 5,
"from" : "b",
"to" : "c",
"message" : "b to c2",
"createdAt" : ISODate("2015-06-06T16:46:32.789Z"),
"updatedAt" : ISODate("2015-06-06T16:46:32.789Z")
}
現在,我想得到一個文件與最近來自於組合。例如:
{
"_id" : 1,
"from" : "a",
"to" : "b",
"message" : "a to b",
"createdAt" : ISODate("2015-06-06T16:42:32.789Z"),
"updatedAt" : ISODate("2015-06-06T16:42:32.789Z")
}
{
"_id" : 4,
"from" : "a",
"to" : "c",
"message" : "a to c2",
"createdAt" : ISODate("2015-06-06T16:45:32.789Z"),
"updatedAt" : ISODate("2015-06-06T16:45:32.789Z")
}
{
"_id" : 5,
"from" : "b",
"to" : "c",
"message" : "b to c2",
"createdAt" : ISODate("2015-06-06T16:46:32.789Z"),
"updatedAt" : ISODate("2015-06-06T16:46:32.789Z")
}
我已經試過這樣:
db.collection.aggregate({$match:{$or:[{"from":"552e5d7b62c6a4c67093be5d"},{"to":"552e5d7b62c6a4c67093be5d"}]}})
與代碼的任何幫助表示讚賞。
@chridam了一個錯字。問題已更新。請考慮_id,createdAt,updatedAt作爲唯一鍵。 –