mongodb聚合操作(aggregation)

存储示例数据:
在这里插入图片描述

db.movies.insertOne({
  fullplot: 'In a cyberpunk vision of the future, man has developed the technology to create replicants, human clones used to serve in the colonies outside Earth but with fixed lifespans. In Los Angeles, 2019, Deckard is a Blade Runner, a cop who specializes in terminating replicants. Originally in retirement, he is forced to re-enter the force when four replicants escape from an off-world colony to Earth.',
  imdb: { rating: '8.2', votes: '419589', id: '83658' },
  year: '1982',
  plot: 'A blade runner must pursue and try to terminate four replicants who stole a ship in space and have returned to Earth to find their creator.',
  genres: [ 'Sci-Fi', 'Thriller' ],
  rated: 'R',
  metacritic: '88',
  title: 'Blade Runner',
  lastupdated: '2015-09-04 00:05:51.990000000',
  languages: [ 'English', 'German', 'Cantonese', 'Japanese', 'Hungarian' ],
  writers: [
    'Hampton Fancher (screenplay)',
    'David Webb Peoples (screenplay)',
    'Philip K. Dick (novel)'
  ],
  type: 'movie',
  tomatoes: {
    viewer: { rating: '4', numReviews: '331213', meter: '91' },
    dvd: '1997-08-27T00:00:00.000Z',
    critic: { rating: '8.5', numReviews: '102', meter: '90' },
    lastUpdated: '2015-09-12T17:48:21.000Z',
    consensus: "Misunderstood when it first hit theaters, the influence of Ridley Scott's mysterious, neo-noir Blade Runner has deepened with time. A visually remarkable, achingly human sci-fi masterpiece.",
    rotten: '10',
    production: 'Warner Bros. Pictures',
    fresh: '92'
  },
  poster: 'https://m.media-amazon.com/images/M/MV5BNzQzMzJhZTEtOWM4NS00MTdhLTg0YjgtMjM4MDRkZjUwZDBlXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_SY1000_SX677_AL_.jpg',
  num_mflix_comments: '1',
  released: '1982-06-25T00:00:00.000Z',
  awards: {
    wins: '13',
    nominations: '15',
    text: 'Nominated for 2 Oscars. Another 11 wins & 15 nominations.'
  },
  countries: [ 'USA', 'Hong Kong', 'UK' ],
  cast: [
    'Harrison Ford',
    'Rutger Hauer',
    'Sean Young',
    'Edward James Olmos'
  ],
  directors: [ 'Ridley Scott' ],
  runtime: '117'
});
`

在这里插入图片描述
聚合查询:

db.movies.aggregate([
  // First Stage
  { $project: { _id: 0, genres: 1, imdb: 1, title: 1 } },
  // Second Stage
  { $unwind: "$genres" },
  // Third Stage
  { $group:
    { _id: "$genres",
      averageGenreRating: { $avg: "$imdb.rating" }
    }
  },
   // Fourth Stage
   { $sort: { averageGenreRating: -1 } }
] )

在这里插入图片描述
结果:

{ "_id" : "Thriller", "averageGenreRating" : null }
{ "_id" : "Sci-Fi", "averageGenreRating" : null }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值