2015-06-20 24 views
1

我試圖查詢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"}]}}) 

與代碼的任何幫助表示讚賞。

+0

@chridam了一個錯字。問題已更新。請考慮_id,createdAt,updatedAt作爲唯一鍵。 –

回答

1

使用以下聚合管道得到想要的結果:

db.collection.aggregate([ 
    { 
     "$sort": { 
      "updatedAt": -1 
     } 
    }, 
    { 
     "$group": { 
      "_id": { 
       "to": "$to", 
       "from": "$from"     
      }, 
      "id": { "$first": "$_id" }, 
      "message": { "$first": "$message" }, 
      "createdAt": { "$first": "$createdAt" }, 
      "updatedAt": { "$first": "$updatedAt" } 
     } 
    }, 
    { 
     "$project": { 
      "_id" : 0, 
      "id": 1, 
      "from" : "$_id.from", 
      "to": "$_id.to", 
      "message": 1, 
      "createdAt": 1, 
      "updatedAt": 1 
     } 
    } 
]) 
+0

任何快速獲取和替換不同集合中的鍵的方法? 例如:{ 「_id」:4, 「from」:{id:「a」,「name」:「a」}, 「to」:{id:「c」,「name」:「c 「}, 」message「:」a to c2「, 」createdAt「:ISODate(」2015-06-06T16:45:32.789Z「), 」updatedAt「:ISODate(」2015-06-06T16:45 :32.789Z「) } –

+0

@ Prasad.CH聽起來像一個很好的問題,你能爲此創建一個新問題嗎? – chridam