MongoDB のタイムスタンプで並べ替え
今日の投稿では、MongoDB でタイムスタンプを並べ替えるさまざまな方法について説明します。
MongoDB のタイムスタンプで並べ替え
sort() メソッドは、MongoDB 内のドキュメントをソートします。 このメソッドは、フィールドのリストとそれらをソートする順序を含むドキュメントを受け入れます。
1 と -1 はソート順を指定します。 昇順の場合は 1 を使用します。 降順の場合は、-1 を使用します。
構文:
db.collection_name.find().sort({ field_name : 1 | -1 })
この場合、ソートを実行したいコレクションは collection_name で指定されます。 ASC または DESC のいずれかでソートする必要があるフィールドは、field_name で指定されます。
ソート順を指定しない場合、sort() メソッドは昇順でページを表示します。 不安定な並べ替えは、同じデータ セットに適用されるたびに異なる結果をもたらします。
インデックスを利用して、MongoDB はソート操作の結果を見つけることができます。 インデックス スキャンでソート順を決定できない場合、MongoDB は top-k ソート アルゴリズムを実行します。
前のアイデアをよりよく理解するために、次の例を検討してください。
> db.employees.find().sort({ "joining_date" : -1 })
employees コレクションの入社日に従って、上記の例の従業員を並べ替えています。 入社日列は、従業員の ISO フォーマット の入社日を追跡します。
created_at フィールドに基づいて並べ替えを行いたい場合は、タイムスタンプがあるため、_id を使用することもできます。 それは同じ結果になります。
> db.employees.find().sort({ "_id" : -1 })
or
> db.employees.find().sort({ "create_at" : -1 })
上記のコード行を、MongoDB と互換性のある MongoShell で実行します。 次の結果が表示されます。
{
"_id" : ObjectId("54f612b6029b47919a90cesd"),
"email" : "johndoe@exampledomain.com",
"name" : "John Doe",
"create_at" : "ISODate("2020-07-04T00:00:00Z")",
"joining_date" : "ISODate("2020-07-04T00:00:00Z")"
}
{
"_id" : ObjectId("54f612b6029b47919a97cesd"),
"email" : "smithwarn@exampledomain.com",
"name" : "Smith Warn",
"create_at" : "ISODate("2020-04-28T00:00:00Z")",
"joining_date" : "ISODate("2020-04-28T00:00:00Z")"
}
{
"_id" : ObjectId("54f612b6029b47919a91cesd"),
"email" : "jessicawill@exampledomain.com",
"name" : "Jessica Will",
"create_at" : "ISODate("2019-12-14T00:00:00Z")",
"joining_date" : "ISODate("2019-12-14T00:00:00Z")"
}
Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.
LinkedIn