2016-12-02 86 views
0

我卡在查詢方案中。 我在Mongodb中有一個json結構,我將不得不根據元素「索引」查詢文檔。僅檢索位於Mongodb中的數組的索引值中的數據

{"List" : { 
"List1" : [11,12,13,14,15,16], 
"List2" : [11,11,11,11,11,11] 
}, 
"Values" : ["APPLE", "ORANGE", "BANANA", "MANGO", "PAPAYA", "KIWI"], 
"Index" : [1,2,3,1,2,3] 
} 

過濾器應基於「索引」,它是'1',我想顯示如下。

{"List" : { 
"List1" : [11,14], 
"List2" : [11,11] 
}, 
"Values" : ["APPLE","MANGO"], 
"Index" : [1,1] 
} 
下面

是我執行

db.getCollection('TEST').find({"Index": 3} , 
{ "Values": 1,"List":1,"Index": 1, "Index.$": 1} 
) 

我得到的所有數據,除了只有一個索引值,因爲我給了位置參數的查詢(「指數$」:1)

+0

可能重複://計算器。 com/questions/31164156/zip-arrays-with-mongodb) – styvane

回答

1

隨着當前蒙戈3.4版本,你可以$zip結合$range生成的索引和域的陣列,$filter以匹配索引字段和$addFields添加到原始域。

最後一步是$map每個基於匹配索引字段與[郵編陣列用的MongoDB](HTTP $arrayElemAt

aggregate([{ 
    $addFields: { 
     match: { 
      $filter: { 
       input: { 
        $zip: { 
         inputs: ["$Index", { 
          $range: [0, { 
           $size: "$Index" 
          }] 
         }] 
        } 
       }, 
       as: "val", 
       cond: { 
        $eq: [{ 
         $arrayElemAt: ["$$val", 0] 
        }, 1] 
       } 
      } 
     } 
    } 
}, { 
    $project: { 
     "List": { 
      "List1": { 
       $map: { 
        input: "$match", 
        as: "index", 
        in: { 
         $arrayElemAt: ["$List.List1", { 
          $arrayElemAt: ["$$index", -1] 
         }] 
        } 
       } 
      }, 
      "List2": { 
       $map: { 
        input: "$match", 
        as: "index", 
        in: { 
         $arrayElemAt: ["$List.List2", { 
          $arrayElemAt: ["$$index", -1] 
         }] 
        } 
       } 
      } 
     }, 
     "Values": { 
      $map: { 
       input: "$match", 
       as: "index", 
       in: { 
        $arrayElemAt: ["$Values", { 
         $arrayElemAt: ["$$index", -1] 
        }] 
       } 
      } 
     }, 
     "Index": { 
      $map: { 
       input: "$match", 
       as: "index", 
       in: { 
        $arrayElemAt: ["$Index", { 
         $arrayElemAt: ["$$index", -1] 
        }] 
       } 
      } 
     }, 
     _id: 0 
    } 
}]).pretty(); 
+0

非常感謝,我會盡快檢查並更新你。 – Sandy