MongoDB聚合|过滤数组元素

时间:2020-05-29 14:22:10

标签: mongodb

我在名为“电影”的Mongo集合中拥有以下JSON文档。

{
  "_id": "5ed0c9700b9e8b0e2c542054",
  "movie_name": "Jake 123",
  "score": 20,
  "director": "Jake"
},
{
  "_id": "5ed0a9840b9e8b0e2c542053",
  "movie_name": "Avatar",
  "director": "James Cameroon",
  "score": 50,
  "boxoffice": [
    {
      "territory": "US",
      "gross": 2000
    },
    {
      "territory": "UK",
      "gross": 1000
    }
  ]
},
{
  "_id": "5ed0a9630b9e8b0e2c542052",
  "movie_name": "Titanic",
  "score": 100,
  "director": "James Cameroon",
  "boxoffice": [
    {
      "territory": "US",
      "gross": 1000
    },
    {
      "territory": "UK",
      "gross": 500
    }
  ],
  "actors": [
    "Kate Winselet",
    "Leonardo De Caprio",
    "Rajinikanth",
    "Kamalhaasan"
  ]
}

我正在尝试运行以下汇总查询,如下所示。

1)我正在尝试运行以下查询,以查找在英国票房收入超过800的电影。结果很好。但是,如何删除随附有US的数组文档。

db.movies.aggregate([
    { $match: {"boxoffice.territory":"UK"} },
    { $project: {"title" : "$movie_name",
                 "director" : 1, 
                 "boxoffice" : { 
                    $filter: {
                         input: "$boxoffice",
                         as: "bo",
                         cond: { $gte: ["$$bo.gross" , 800]
                        }
                    }
                 } 
             }
    },
    { $match: {"boxoffice.territory":"UK"} }
])

上面的查询返回结果如下。

{
  "_id": "5ed0a9840b9e8b0e2c542053",
  "director": "James Cameroon",
  "title": "Avatar",
  "boxoffice": [
    {
      "territory": "US",
      "gross": 2000
    },
    {
      "territory": "UK",
      "gross": 1000
    }
  ]
}

但是,我想在票房中排除“领土”:“美国”文件。我无法正常工作。

2)我运行以下查询,以查找各个电影所在国家/地区的最大集合。

db.movies.aggregate([
    {$match: {"boxoffice" : { $exists: true, $ne : []}}},
    {$project: {
                "title":"$movie_name", "max_boxoffice": {$max : "$boxoffice.gross"}, 
                "territory" : "$boxoffice.territory" } }
          ])

我得到如下结果。如何获得正确的领土?

{
    "_id" : ObjectId("5ed0a9630b9e8b0e2c542052"),
    "title" : "Titanic",
    "max_boxoffice" : 1000,
    "territory" : [
        "US",
        "UK"
    ]
},
{
    "_id" : ObjectId("5ed0a9840b9e8b0e2c542053"),
    "title" : "Avatar",
    "max_boxoffice" : 2000,
    "territory" : [
        "US",
        "UK"
    ]
}

0 个答案:

没有答案