2016-09-22 62 views
0

我有一個集合,我想要聚合,使特定的字段不同,但也將其他字段數據添加到該聚集的結果。下面是將一些數據添加到不同的查詢中mongodb

{ 
     "_id": ObjectId("57d6bc99e4b014fc13cf9579"), 
     "_class": "hbservlet.FinalSubmissions", 
     "active": true, 
     "mappedTracks": 
     [ 
      { "position": 0, "title": "01. Ain't No Time.mp3", "url": "/published/music/tr157d6bc99e4b014fc13cf9579_.aac" }, 
      { "position": 1, "title": "02. In Her Mouth.mp3", "url": "/published/music/tr257d6bc99e4b014fc13cf9579_.aac" }, 
      { "position": 2, "title": "03. Maybach.mp3", "url": "/published/music/tr357d6bc99e4b014fc13cf9579_.aac" } 
     ], 
     "createdBy": ObjectId("57d6bb99b17ee01a5427af08"), 
     "userId": ObjectId("57d6bb99b17ee01a5427af08"), 
     "artistname": "test", 
    }, { 
     "_id": ObjectId("14d6bc99ebc942fc13cf9579"), 
     "_class": "hbservlet.FinalSubmissions", 
     "active": false, 
     "mappedTracks": [ 
      { "position": 0, "title": "partysong.mp3", "url": "/published/music/tr114d6bc99ebc942fc13cf9579_.aac" }, 
      { "position": 1, "title": "outside", "url": "/published/music/tr214d6bc99ebc942fc13cf9579_.aac" },], 
     "createdBy": ObjectId("57d6bb99b17ee01a5427af08"), 
     "userId": ObjectId("57d6bb99b17ee01a5427af08"), 
     "artistname": "mynameismyname", 
    } 

我用的是不同的查詢(db.published.distinct(「mappedTracks」))來收集我收藏的一個例子所有mappedTracks,所以我得到這個

{ "position": 0, "title": "01. Ain't No Time.mp3", "url": "/published/music/tr157d6bc99e4b014fc13cf9579_.aac" }, 
{ "position": 1, "title": "02. In Her Mouth.mp3", "url": "/published/music/tr257d6bc99e4b014fc13cf9579_.aac" }, 
{ "position": 2, "title": "03. Maybach.mp3", "url": "/published/music/tr357d6bc99e4b014fc13cf9579_.aac" }, 
{ "position": 0, "title": "partysong.mp3", "url": "/published/music/tr114d6bc99ebc942fc13cf9579_.aac" }, 
{ "position": 1, "title": "outside", "url": "/published/music/tr214d6bc99ebc942fc13cf9579_.aac" } 

這是我想要的結果,但我也想添加它所屬的文檔的_id,userID,artistname到創建的新對象。

回答

0

您可以試試MongoDB aggregation運營商$unwind$group。例如:

db.collection.aggregate([ 
      {$unwind:"$mappedTracks"}, 
      {$group:{_id: 
         {mappedTracks:"$mappedTracks", 
         id:"$_id", 
         userId:"$userId", 
         artistname:"$artistname" 
         } 
        } 
      } 
]) 

請注意,這是假設您現在想要所有這四個字段的不同值組合。如果您只想要區分mappedTracks,則必須決定如何處理重複值爲userIdartistname。如果是這種情況,請參見$first運營商在重複情況下使用第一個值。

參見集成算$project如果您想$group後重命名一些字段。

如果此查詢是針對您的用例的常用查詢,我會建議您重新考慮您的Data Modelling or Document Structure

+0

謝謝婉,這指出我的方向是正確的。我正在重新考慮我的文檔結構以獲得更高效的系統。 –

相關問題