2016-01-22 59 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