2015-10-15 118 views
0

我的目標是建立內部陣列主陣列當搜索用戶標識爲1 下面是我的數據MongoDB的多陣列個別陣列上搜索

{ "_id" : 2, 
    "name" : "test1", 
    "data" :[{"_id" : "1","file" : "nic", "userid" : [1,2 ]}, 
      {"_id" : "2","file" : "nic1","userid" : [1 ] }, 
      {"_id" : 3,"file" : "nick2","userid" : [1,2 ]} 
]}, 

{ "_id" : 3, 
    "name" : "test2", 
    "data" : [{"_id" : "1","file" : "nic","userid" : [1,2 ] }, 
      {"_id" : "2","file" : "nic1", "userid" : [3,2 ] } 
    ]} 

需要走出去把儘可能

{"_id" : 1,"file" : "nic", "userid" : [1,2 ],"main_name" : "test1","main_id" : 2}, 
{"_id" : 2,"file" : "nic1","userid" : [1 ] ,"main_name" : "test1","main_id" : 2 }, 
{"_id" : 3,"file" : "nick2","userid" : [1,2 ],"main_name" : "test2","main_id" : 3}, 
{"_id" : 1,"file" : "nic","userid" : [1,2 ] ,"main_name" : "test2" ,"main_id" : 3} 
+1

又是什麼問題? – m02ph3u5

回答

1

基本上與你的last question相同的答案,但沒有$group來重建陣列和使用$project,而是從已經非規範化的數組元素重構文檔。

$collection->aggregate(array(
    array('$match' => array("data.userid" => 1)), 
    array('$unwind' => '$data'), 
    array('$match' => array('data.userid' => 1)), 
    array(
     '$project' => array(
      '_id' => '$data._id', 
      'nic' => '$data.nic', 
      'user_id' => '$data.user_id', 
      'main_name' => '$name', 
      'main_id' => '$_id' 
     ) 
    ) 
)) 
+0

同樣的事情,如果我想獲得所有記錄不論userid.how我們可以做到 –

+0

@sasikanth那麼「同樣的事情」,如果你有其他問題,然後[問另一個問題](http://stackoverflow.com/questions/ask )(這是它的工作原理,因爲這不是討論板或論壇,而是一個問答的資源,所以你需要提出一個明確的問題)。而且,目前還不清楚你在問什麼,因爲到目前爲止你的整個觀點都是關於用所謂的「userid」值「過濾」結果。那麼,爲什麼不只是刪除'$ match'語句,如果你只是想要一切?或者問另一個問題。這是什麼問題, –