存储示例数据:
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 }