今回は MongoDB で 最大値 または 最小値 を取得する方法についてまとめます。
前提データ
test データベース の sample コレクション に以下のようなデータがある前提で、
price の最大値または最小値を取得するサンプルを見ていきます。
> use test
switched to db test
> db.sample.find()
{ "_id" : ObjectId("59fc8cca060ed81c5c835c7a"), "item" : "ABC", "price" : 120 }
{ "_id" : ObjectId("59fc8cca060ed81c5c835c7b"), "item" : "ABC", "price" : 120 }
{ "_id" : ObjectId("59fc8cca060ed81c5c835c7c"), "item" : "BCD", "price" : 150 }
{ "_id" : ObjectId("59fc8cca060ed81c5c835c7d"), "item" : "ABC", "price" : 120 }
{ "_id" : ObjectId("59fc8cca060ed81c5c835c7e"), "item" : "BCD", "price" : 150 }
{ "_id" : ObjectId("59fc8cca060ed81c5c835c7f"), "item" : "BCD", "price" : 150 }
{ "_id" : ObjectId("59fc8cca060ed81c5c835c80"), "item" : "ABC", "price" : 120 }
{ "_id" : ObjectId("59fc8cca060ed81c5c835c81"), "item" : "BCD", "price" : 150 }
{ "_id" : ObjectId("59fc8cca060ed81c5c835c82"), "item" : "CDE", "price" : 180 }
最大値を取得するサンプルコード
複雑なことはする必要がありません。
昇順にソート (L.8) して最初の1件 (L.10) を取得すれば、最大値が取得できます。
サンプルコードでは最後に $project を行っていますが、取得されるデータ量が少なければあえて実行する必要はないかもしれません。
サンプルコード
var MongoClient = require("mongodb").MongoClient;
var moment = require("moment");
var CONNECTION_URL = "mongodb://localhost:27017/test";
MongoClient.connect(CONNECTION_URL).then((db) => {
db.collection("sample").aggregate([{
$sort: { price: -1 }
}, {
$limit: 1
}, {
$project: { _id: 0, price: 1 }
}]).toArray((err, docs) => {
if (err) throw err;
console.log(JSON.stringify(docs));
});
});
実行結果
[{"price":180}]
最小値を取得するサンプルコード
上記の「最大値を取得するサンプルコード」において $sort: { price: -1 } を { price: 1 } とすれば最小値を取得できます。
要するにソート順を変更するだけです。
サンプルコード
var MongoClient = require("mongodb").MongoClient;
var moment = require("moment");
var CONNECTION_URL = "mongodb://localhost:27017/test";
MongoClient.connect(CONNECTION_URL).then((db) => {
db.collection("sample").aggregate([{
$sort: { price: 1 }
}, {
$limit: 1
}, {
$project: { _id: 0, price: 1 }
}]).toArray((err, docs) => {
if (err) throw err;
console.log(JSON.stringify(docs));
});
});
実行結果
[{"price":120}]
今回は MongoDB で 最大値 または 最小値 を取得する方法 についてまとめました。 ポイントは「sort → limit」で取得することです。 参考になったでしょうか?
本記事がお役に立つと嬉しいです!!
最後に… このブログに興味を持っていただけた方は、 ぜひ 「Facebookページ に いいね!」または 「Twitter の フォロー」 お願いします!!