【问题标题】:$setIntersection for new set of array to be searched return count matched$setIntersection 用于搜索的新数组集返回匹配的计数
【发布时间】:2023-03-21 02:23:01
【问题描述】:

对于在美国上映且tomato.viewer.rating 大于或等于3 的电影,计算一个名为num_favs 的新字段,该字段表示电影演员字段中出现的收藏夹数。

我不确定如何进一步进行,请您帮忙

 favorites = 
    ["Sandra Bullock",
    "Tom Hanks",
    "Julia Roberts",
    "Kevin Spacey",
    "George Clooney"]

     db.movies.aggregate([
   { $match:{
     'tomatoes.viewer.rating':{$gte:3},
     "countries":"USA"
         }
    }
    ]). 

【问题讨论】:

    标签: mongodb-query aggregation-framework


    【解决方案1】:
    var favorites =  [
      "Sandra Bullock",
      "Tom Hanks",
      "Julia Roberts",
      "Kevin Spacey",
      "George Clooney"]
    
    
    db.movies.aggregate([
        {
            $match: 
            {
                "tomatoes.viewer.rating": { $gte:3 },
                "cast": 
                { 
                    $in:["Sandra Bullock","Tom Hanks","Julia Roberts","Kevin Spacey","George Clooney"]
                }
            }
        },
        {
            $project:
            {
                _id:0,
                "tomatoes.viewer.rating":1,
                title:1,
                cast:1,
                num_favs:
                    {
                        $size:
                        {
                            $setIntersection:["$cast",favorites]
                        }
                    }
            }
        },
        {
            $sort:
            {
                "num_favs":-1,
                "tomatoes.viewer.rating":-1,
                title:-1
            }
        }
        ])
    

    我认为这可能会为您提供正确的答案。我发现,如果你不匹配演员表,那么你会在 num_favs 中得到空白或 null,但如果你 $match 演员表,那么你会得到正确的答案。如果有任何变化,请告诉我。谢谢。

    【讨论】:

      【解决方案2】:

      这是我解决这个问题的管道

      [
       {$match: {
       countries: 'USA',
       'tomatoes.viewer.rating': {
        $gte: 3
       },
       cast: {
        $type: 'array'
       }
      }},
      
       {$project: {
       title: 1,
       'tomatoes.viewer.rating': 1,
       num_favs: {
        $size: {
         $setIntersection: [
          '$cast',
          [
           'Sandra Bullock',
           'Tom Hanks',
           'Julia Roberts',
           'Kevin Spacey',
           'George Clooney'
          ]
         ]
        }
       }
      }}, 
      
      {
      $sort: {
       num_favs: -1,
       'tomatoes.viewer.rating': -1,
       title: -1
      }}, 
      
      {$skip: 24}] 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-12
        • 2014-08-19
        • 2016-10-31
        • 1970-01-01
        • 1970-01-01
        • 2018-05-09
        • 2013-07-29
        • 2017-12-01
        相关资源
        最近更新 更多