我有一組包含以下格式的電影資訊的檔案:
{
"_id": "100063",
"_rev": "1-90d4068b3946fe809a9c9022f1e1c354",
"title": "The Love She Sought",
"year": 1990,
"rating": null,
"runtime": "100 min",
"genre": [
"Drama"
],
"director": "Joseph Sargent",
"writer": [
"Jon Hassler (novel)",
"Ron Cowen (teleplay)",
"Daniel Lipman (teleplay)"
],
"cast": [
"Angela Lansbury",
"Denholm Elliott",
"Cynthia Nixon",
"Gary Hershberger"
],
"poster": "http://ia.media-imdb.com/images/M/MV5BMjEwODQzODc2Nl5BMl5BanBnXkFtZTgwMDY2ODk1MDE@._V1_SX300.jpg",
"imdb": {
"rating": 7.9,
"votes": 747,
"id": "tt0100063"
}
}
問題是:找出 2007 年上映的電影的平均票數
我嘗試了 $unwind 但它不起作用,這是我的代碼
db.movies.aggregate([
{ $unwind: "$imdb"},
{$group : { _id: "$year",
avgVote : { $avg : "$imdb.votes" }
}},
{ $match: {"year": 2007}
])
uj5u.com熱心網友回復:
您不需要用于將陣列欄位解構為多個檔案的$unwind階段,而該欄位不是陣列,而是物件。$unwindimdb
并將$matchstage移到第一stage,盡快過濾檔案,以獲得更好的查詢性能。
db.collection.aggregate([
{
$match: {
"year": 2007
}
},
{
$group: {
_id: "$year",
avgVote: {
$avg: "$imdb.votes"
}
}
}
])
示例 Mongo Playground
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414714.html
標籤:
