2016-01-22 60 views
2

所以,在我的MongoDB我有一個看起來像這樣幾個文件:如何在MongoDB中排列查詢

{ 
    "_id" : ObjectId("56a17b7f5f7ecf32c5ee0077"), 
    "MediaID" : "302048", 
    "MediaName" : "El Viejo y el Mar", 
    "MediaTypeID" : "384", 
    "MediaTypeName" : "Movie", 
    "Rating" : NumberInt(0), 
    "Description" : "La versión cinematográfica de la obra inmortal de Ernest Hemingway, sobre un viejo pescador cubano que logra atrapar un pescado gigantesco que lo arrastra lejos de la orilla.", 
    "MediaWebLink" : "", 
    "Duration" : "5160", 
    "FileID" : "523852", 
    "like_counter" : NumberInt(0), 
    "EntryId" : "", 
    "Tags" : [ 
     { 
      "Key" : "Clasificacion", 
      "Value" : "B" 
     }, 
     { 
      "Key" : "Genre", 
      "Value" : "Drama|Clásicas" 
     }, 
     { 
      "Key" : "Pais", 
      "Value" : "Estados Unidos" 
     }, 
     { 
      "Key" : "Directors", 
      "Value" : "John Sturges" 
     }, 
     { 
      "Key" : "Actors", 
      "Value" : "Spencer Tracy" 
     }, 
     { 
      "Key" : "Distribuidor", 
      "Value" : "Warner" 
     }, 
     { 
      "Key" : "Subtitles", 
      "Value" : "Español" 
     }, 
     { 
      "Key" : "Audio Version", 
      "Value" : "Inglés" 
     }, 
     { 
      "Key" : "Sub-Genre", 
      "Value" : "" 
     }, 
     { 
      "Key" : "Palabras Clave", 
      "Value" : "" 
     }, 
     { 
      "Key" : "Prizes", 
      "Value" : "" 
     } 
    ], 
    "Metas" : [ 
     { 
      "Key" : "Nombre original", 
      "Value" : "The Old Man And The Sea" 
     }, 
     { 
      "Key" : "Synopsis corta", 
      "Value" : "Es la historia de un viejo pescador cubano que logra atrapar un pescado gigantesco que lo arrastra lejos de la orilla." 
     }, 
     { 
      "Key" : "Duracion", 
      "Value" : "01:26:00" 
     }, 
     { 
      "Key" : "Ano", 
      "Value" : "1958" 
     }, 
     { 
      "Key" : "Score de titulo", 
      "Value" : "4" 
     } 
    ], 
    "AdvertisingParameters" : [ 

    ] 

} 

裏面的文件,有一個名爲標籤的數組,其中一個關鍵= Distribuidor和值=華納 我需要的是做一個查詢,在那裏我可以獲得我擁有的所有文檔的所有區別「distribuidor」值。

到目前爲止,我已經試過這樣:

db.catalogo.distinct('Tags.Value', { 'Tags.Key': 'Distribuidor' }) 

但這讓我所有的值,而不是隻爲「distribuidor」值。

有什麼建議嗎?

回答

0

請嘗試以下aggregation pipeline

db.catalogo.aggregate({ 
    $unwind: "$Tags" 
}, { 
    $match: { 
     "Tags.Key": "Distribuidor" 
    } 
}, { 
    $group: { 
     _id: "$Tags.Value" 
    } 
}) 

簡單地說,我們有一個unwind,擴大你在多個文檔Tags陣列;然後match,篩選出的標籤沒有"Distribuidor"作爲Key,然後group,在這種情況下作爲不同的Value(你可以很容易地爲每個值添加一個count,但這不是你問的)。輸出將會像

{ "_id" : "Warnero" } 
{ "_id" : "Warner" } 
+0

這正是我所尋找的,非常感謝! –

0

如果我理解的問題,試試這個,UPD:

db.catalogo.find({}, { 'Tags.Key': 1 }) 
+0

它沒有工作。 2016-01-22T14:38:38.770-0600 E QUERY [thread1]錯誤:distinct命令的第一個參數必須是字符串,但是是對象: [email protected]/mongo/shell/collection.js :1628:1 @(shell):1:1 –

+0

對不起,我更新了 – alex10