2012-08-02 75 views
2

我有這種簡單分貝,包含元素的子集:mongodb的序列化的子集結果

{ "_id" : ObjectId("5019eb2356d80cd005000000"), 
    "photo" : "/pub/photos/file1.jpg", 
    "comments" : [ 
     { 
      "name" : "mike", 
      "message" : "hello to all" 
     }, 
     { 
      "name" : "pedro", 
      "message" : "hola a todos" 
     } 
    ] 
}, 
{ "_id" : ObjectId("5019eb4756d80cd005000001"), 
    "photo" : "/pub/photos/file2.jpg", 
    "comments" : [ 
     { 
      "name" : "luca", 
      "message" : "ciao a tutti" 
     }, 
     { 
      "name" : "stef", 
      "message" : "todos bien" 
     }, 
     { 
      "name" : "joice", 
      "message" : "vamos a las playa" 
     } 
    ] 
} 

當我執行一個子集的發現: db.photos.find({},{ 「comments.name」:1 })

林收到此結構:

[ 
    { 
     "_id" : ObjectId("5019eb2356d80cd005000000"), 
     "comments" : [ 
      { 
       "name" : "mike" 
      }, 
      { 
       "name" : "pedro" 
      } 
     ] 
    }, 
    { 
     "_id" : ObjectId("5019eb4756d80cd005000001"), 
     "comments" : [ 
      { 
       "name" : "luca" 
      }, 
      { 
       "name" : "stef" 
      }, 
      { 
       "name" : "joice" 
      } 
     ] 
    } 
] 

但我希望得到一個簡單的一維數組,像這樣的(或類似):

[ 
    { 
     "name" : "mike" 
    }, 
    { 
     "name" : "pedro" 
    }, 
    { 
     "name" : "luca" 
    }, 
    { 
     "name" : "stef" 
    }, 
    { 
     "name" : "joice" 
    } 
] 

我需要蒙戈PHP的官方驅動程序來實現此查詢,但語言並不重要,我只是想通過什麼邏輯來理解,我可以通過蒙戈完成這個殼

TNK!

回答

2

最簡單的方法是使用distinct()

>db.photos.distinct("comments.name"); 
[ "mike", "pedro", "joice", "luca", "stef" ] 

這是一個使用JavaScript的另一個例子:

// Array to save results 
> var names = [] 

// Find comments and save names 
> db.photos.find({},{"comments.name":1}).forEach(
      function(doc) { doc.comments.forEach(
       function(comment) {names.push(comment.name)}) 
      }) 

// Check the results 
> names 
[ "mike", "pedro", "luca", "stef", "joice" ] 

下面是一個使用在即將到來的MongoDB 2.2新聚合框架的例子:

db.photos.aggregate(
    { $unwind : "$comments" }, 
    { $group : { 
    _id: "names", 
    names: { $addToSet : "$comments.name" } 
    }}, 
    { $project : { 
    '_id' : 0, 
    'names' : 1, 
    }} 
) 
+0

謝謝Stennie 我認爲有可能是一個更簡單的解決方案,但在這之上對於文檔的幾個深度級別來說是很好的。 (這個解決方案將需要每個深度的foreach循環) 或者我認爲也許我錯了,因爲我創建了我的數據庫設計,也許我應該使用 – StefanoCudini 2012-08-03 00:09:35

+1

@StefanoCudini:添加了一個使用MongoDB中的聚合框架的例子2.2rc0 。在這種情況下,實際上不需要位置運算符..只需要查找和分組獨特的值。 – Stennie 2012-08-03 02:26:57

+0

好的解決方案!但我使用的是mongodb而不是debian squeeze服務器,不幸的是我不能使用更新版本的1.4.4 我是一個新手MongoDB,我想也許我在項目應用程序中是錯誤的,也許我應該使用單獨的集合然後將其放入dbref「comments」數組中:[..] 這樣我就可以檢索包含每個文檔上所有註釋的單個查詢。 尚未能做出正確的選擇,您認爲最好的解決方案是什麼? 或者如果2.2版本正在快速增長並且更好地升級您的版本而不是跟隨debian存儲庫? – StefanoCudini 2012-08-05 00:42:37