2014-02-18 94 views
0

我想取回帳戶陣列如果查詢找到角色的「精英」檢索特定領域的貓鼬

我嘗試用

db.users.aggregate(
{ $match : { "account.role" : "Elite" } } 
); 

但我有所有的對象......

{ 
"_id" : ObjectId("7623902143981943"),   
"account" : [ 
    { 
     "role" : "Elite",    
     "action" : [ 
      "create", 
      "read", 
      "update", 
      "delete" 
     ], 
     "extra" : { 
      account:[1,2,3,4] 
     } 
    }, 
{ 
     "role" : "User",    
     "action" : [ 
      "create", 
      "read", 
      "update", 
      "delete" 
     ], 
     "extra" : { 
      account:[10] 
     } 
    } 
],  

}

如果是來自查詢的肯定結果,我可以只檢索額外的數組(帳戶:[1,2,3,4])嗎?或者我必須解析收到的對象? (架構是非常簡單的,但是我有很多角色)

回答

1

必須使用$project$unwind

//Order of $unwind and $match matters 
db.users.aggregate(
{$unwind: "$account"}, 
{$match : { "account.role" : "Elite" }}, 
{$project : { "extra.account" : 1}} 
); 

解釋

$放鬆身心分裂的數組不同的元素。看效果

db.users.aggregate({$unwind: "$account"}) 

然後你用{「account.role」:「Elite」}匹配元素。見效果:

db.users.aggregate(
{$unwind: "$account"}, 
{$match : { "account.role" : "Elite" }} 
); 

然後你終於項目只是所需的字段

db.users.aggregate(
{$unwind: "$account"}, 
{$match : { "account.role" : "Elite" }}, 
{$project : { "extra.account" : 1}} 
); 

//You can also remove the _id filed (included by default with: 
db.users.aggregate(
{$unwind: "$account"}, 
{$match : { "account.role" : "Elite" }}, 
{$project : { _id: 0, "extra.account" : 1}} 
); 

OLD ANSWER

您必須使用投影: db.users.aggregate( { $ match:{「account.role」:「Elite」}}, {$ project:{「extra.account」:1}} );

此外,如果你只是配套文件,有沒有必要使用聚合framewrok,你可以只使用:

// No projection here 
db.users.find({"account.role" : "Elite"}) 

// Only returns the _id field + "extra.account" field if exists. By default the _id field is included 
db.users.find({"account.role" : "Elite"}, { "extra.account" : 1}) 

// Only returns the "extra.account" field if exists 
db.users.find({"account.role" : "Elite"}, { _id: 0, "extra.account" : 1}) 

MongoDB的文件可以發現herehere

+0

謝謝,但我有這個'錯誤異常:一個流水線階段規範對象必須只包含一個字段.' – Twinsen

+0

我編輯了'aggregate({$ match:..},{$ project:...})'而不是'aggregate({$ match:..,$ project:...})的答案' 。參考可以在這裏找到(http://docs.mongodb.org/manual/core/aggregation-pipeline/) –

+0

再次感謝,但在我的結果中,我有兩個extra.account數組精英和extra.account用戶..我可以只檢索Elite嗎? – Twinsen