2017-04-11 33 views
0

我有這樣的如何檢索選定陣列對象MongoDB中

{ 
    "_id" : ObjectId("58eb32fb58bbf720a80daf6f"), 
    "RoleName" : "Admin", 
    "UIList" : [ 
     { 
      "UiName" : "ManageRole", 
      "View" : true, 
      "Edit" : false, 
      "_id" : ObjectId("58eb32fb58bbf720a80daf79") 
     }, 
     { 
      "UiName" : "ManageBuildings", 
      "View" : false, 
      "Edit" : false, 
      "_id" : ObjectId("58eb32fb58bbf720a80daf78") 
     }, 
     { 
      "UiName" : "ManageFacility", 
      "View" : true, 
      "Edit" : false, 
      "_id" : ObjectId("58eb32fb58bbf720a80daf77") 
     } 
    ], 
    "__v" : 0, 
    "Description" : "Full Control", 
    "IsActive" : true 
} 

MongoDB的數據我只想檢索查看:UiName下UIList真:「ManageFacility」的如何檢索。

我試圖得到這個查詢後面的數據,但它檢索Uiname下的所有UIList:,View,Edit值。

db.getCollection("manage_roles_news").find(
    { _id:ObjectId("58eb32fb58bbf720a80daf6f")}, 
    {UIList: {$elemMatch: {UiName: "ManageFacility"}}}); 

如何檢索UIlist Uiname下,只有觀點:「ManageFacility」

誰能告訴我

+0

嘗試'db.getCollection( 「manage_roles_news」)找到( {_id:物件( 「58eb32fb58bbf720a80daf6f」)},{ UIList:{$ elemMatch:{UiName: 「ManageFacility」,查看:真正} }});' – Veeram

+0

嗨,@Veeram這個查詢也返回所有managefacility列 – Vinoth

+0

我只想查看 – Vinoth

回答

1

我不認爲有辦法從positional/elemMatch投影項目的各個字段。它總是解析爲數組元素。

您可以嘗試下面的聚合項目字段。下面的查詢使用$filter運算符來找到匹配的數組值,這些值被傳送到$arrayAtElem以返回第一個元素(0)並將匹配文檔傳遞給$let運算符,然後選擇View屬性。

db.getCollection("manage_roles_news").aggregate(
    { $match: { _id: ObjectId("58eb32fb58bbf720a80daf6f") } }, 
    { $project: { 
     _id:0, 
     View: 
     { $let: { 
      vars: { 
       mElement: { 
       $arrayElemAt: [{ 
          $filter: { 
           input: "$UIList", 
           as: "fElement", 
           cond: { 
            $eq: ["$$fElement.UiName", "ManageFacility"] 
           } 
          } 
         }, 0] 
        } 
       }, 
      in: {$cond:["$$mElement.View", 1, 0]} 
      } 
     } 
    } 
}) 
+0

它正在工作.. – Vinoth

+0

1.在'$ project'階段添加'_id:0'來排除'_id' 。 2用'{$ cond:[「$$ mElement.View」,1,0]替換'「$$ mElement.View」'' – Veeram

+0

可以在另一個回答中發表此問題 – Vinoth