Py学习  »  MongoDB

Mongodb基于另一个数组元素过滤数组

Madhuprathap • 5 年前 • 1948 次点击  

{
"_id" : 1,
"Quality" : [ 
        "HIGH", 
        "LOW", 
        "LOW", 
        "HIGH"
    ],
    "Pages" : [ 
        10, 
        10, 
        12, 
        17
    ]
}

我需要结果作为

{
"_id" : 1,
"HIGH" : 27
"LOW" : 22
}

我想用 $筛选器 $arrayElemAt公司 ,但在筛选页面属性时无法获取索引位置

high : { $sum:{ $filter: { input: "$Pages", as: "noOfPages", cond: {"$eq":[{ $arrayElemAt: ["$Quality", **Need to pass index position of $pages while filtering**]}, "HIGH"]}}}}

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/54696
 
1948 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Omer Vertman
Reply   •   1 楼
Omer Vertman    5 年前

首先是将两个数组映射为一个数组。

其次是过滤单个数组,使其只包含HIGH(/LOW),并将过滤后的数组减少为单个sum元素。

[{$project: {
  "Quality": {
    $map: {
      input: {$range: [0, {$size: "$Quality"}]},
      as: "idx",
      in: {
        "Quality": { $arrayElemAt: ["$Quality", "$$idx"] },
        "Pages": { $arrayElemAt: ["$Pages", "$$idx"] }
      }
    }
  }
}}, {$project: {
  "HIGH": {
    $reduce: {
      input: {
        $filter: {
          input: "$Quality",
          as: "x",
          cond: {$eq: ["$$x.Quality", "HIGH"]}
        }
      },
      initialValue: 0,
      in: {
        $add: ["$$value", "$$this.Pages"]
      }
    }
  },
  "LOW": {
    $reduce: {
      input: {
        $filter: {
          input: "$Quality",
          as: "x",
          cond: {$eq: ["$$x.Quality", "LOW"]}
        }
      },
      initialValue: 0,
      in: {
        $add: ["$$value", "$$this.Pages"]
      }
    }
  }
}}]

这正是你所要求的:

{
  _id: 1
  HIGH:27
  LOW:22
}
Ashh
Reply   •   2 楼
Ashh    5 年前

您可以使用下面的聚合

db.collection.aggregate([
  { "$project": {
    "Quality": {
      "$map": {
        "input": { "$range": [0, { "$size": "$Quality" }] },
        "in": {
          "Quality": { "$arrayElemAt": ["$Quality", "$$this"] },
          "Pages": { "$arrayElemAt": ["$Pages", "$$this"] }
        }
      }
    }
  }},
  { "$project": {
    "newArrayField": {
      "$map": {
        "input": { "$setUnion": ["$Quality.Quality"] },
        "as": "m",
        "in": {
          "k": "$$m",
          "v": {
            "$filter": {
              "input": "$Quality",
              "as": "d",
              "cond": {
                "$eq": ["$$d.Quality", "$$m"]
              }
            }
          }
        }
      }
    }
  }},
  { "$project": {
    "d": {
      "$arrayToObject": {
        "$map": {
          "input": "$newArrayField",
          "in": {
            "k": "$$this.k",
            "v": { "$sum": "$$this.v.Pages" }
          }
        }
      }
    }
  }}
])

MongoPlayground