1

私はmongoDBが初めてで、問題に遭遇しました。データは公式ドキュメントに従ってインポートされました。
ご覧のとおり、各レストランには成績配列があり、ネストされたドキュメントにはスコア フィールドが含まれています。私がやりたいことは、各レストランの評価の平均スコアに従って、平均スコアが上位のレストランを検索することです。これはmongoDBの集約メソッドを使用する必要があるかもしれませんが、ドキュメントはネストされたドキュメントの状況をカバーしていないため、グーグルで検索しましたが結果はありません. このサイトにも同様の質問がありますが、あまり明確ではありません。

[
 { "_id" : ObjectId("56a9f39cae1902590811dffc"), 
 "address" : { "building" : "284", 
               "coord" : [ -73.9829239, 40.6580753 ], 
               "street" : "Prospect Park West", 
               "zipcode" : "11215" }, 
 "borough" : "Brooklyn", 
 "cuisine" : "American ", 
 "grades" : [ { "date" : ISODate("2014-11-19T00:00:00Z"), "grade" : "A", "score" : 11 }, 
              { "date" : ISODate("2013-11-14T00:00:00Z"), "grade" : "A", "score" : 2 }, 
              { "date" : ISODate("2012-12-05T00:00:00Z"), "grade" : "A", "score" : 13 }, 
              { "date" : ISODate("2012-05-17T00:00:00Z"), "grade" : "A", "score" : 11 } ], 
 "name" : "The Movable Feast", 
 "restaurant_id" : "40361606" },
        ... 
]
4

1 に答える 1

1

mongo シェルを使用して、以下を試し、「collectionname」をレストラン コレクションの名前に変更します。

 db.collectionname.aggregate( { '$unwind' : '$grades' } , { '$group' : { '_id' : '$_id' , 'average' : { $avg : '$grades.score' } } } , { '$sort' : { 'average' : -1 } } , { '$limit' : 1 } )
于 2016-02-01T12:10:08.010 に答える