2016-08-04 7 views
0

私の書類はこのようです。シングルmongodbクエリを見つけて数えてください

{ 
"_id" : ObjectId("572c4bffd073dd581edae045"), 
"name" : "What's New in PHP 7", 
"description" : "PHP 7 is the first new major version number of PHP since 2004. This course shows what's new, and what's changed.", 
"difficulty_level" : "Beginner", 
"type" : "Normal", 
"tagged_skills" : [ 
    { 
     "_id" : "5714e894e09a0f7d804b2254", 
     "name" : "PHP" 
    } 
], 
"created_at" : 1462520831.649, 
"updated_at" : 1468233074.243 } 

最近の5件のドキュメントと合計件数を1つのクエリで取得できますか? 私は、以下のようにこの要件に対して2つのクエリを使用しています。

db.course.find().sort({created_at:-1}).limit(5) 
db.course.count() 

答えて

3

これは、集約フレームワークにとって完璧な仕事です。

db.course.aggregate(
    [ 
     { "$sort": { "created_at": -1 }}, 
     { "$group": { 
      "_id": null, 
      "docs": { "$push": "$$ROOT" }, 
      "count": { "$sum": 1 } 
     }}, 
     { "$project": { "_id": 0, "count": 1, "docs": { "$slice": [ "$docs", 5 ] } }} 
    ] 
) 

あなたのMongoDBサーバーは、あなたが醜いと非効率的なアプローチを使用する必要があり、その後$sliceをサポートしていない場合。

db.course.aggregate(
    [ 
     { "$sort": { "created_at": -1 }}, 
     { "$group": { 
      "_id": null, 
      "docs": { "$push": "$$ROOT" }, 
      "count": { "$sum": 1 } 
     }}, 
     { "$unwind": "$docs" }, 
     { "$limit": 5 } 
    ] 
) 
+0

あなたは$$ ROOTについて少し説明できますか? –

+0

@jarryjafery ['$$ ROOT'](https://docs.mongodb.com/manual/reference/aggregation-variables/#variable.ROOT)はMongoDBのシステム変数で、処理される文書にアクセスすることができます。私はちょっと時間があるときに私の答えに説明を加えます。 – styvane

+0

はいありがとうございます –

-3

いいえ、他の方法はありません。 2つのクエリ - 1つはカウント - 1つは制限付きです。

関連する問題