翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$sort
$sort 更新修飾子は、 $push演算子で使用すると配列要素を順序付けします。指定されたフィールド値または要素自体に基づいて、配列要素を昇順または降順に配置します。
パラメータ
-
field: 変更する配列フィールド。
-
order: 昇順-1または降順1に使用します。
例 (MongoDB シェル)
次の例は、 $sort で 修飾子を使用して新しいクイズスコアを追加し$push、降順でソートされたままにする方法を示しています。
サンプルドキュメントを作成する
db.students.insertOne({
_id: 1,
name: "Bob",
quizzes: [
{ score: 85, date: "2024-01-15" },
{ score: 92, date: "2024-02-10" }
]
});
クエリの例
db.students.updateOne(
{ _id: 1 },
{
$push: {
quizzes: {
$each: [{ score: 78, date: "2024-03-05" }],
$sort: { score: -1 }
}
}
}
)
出力
{
"_id" : 1,
"name" : "Bob",
"quizzes" : [
{ "score" : 92, "date" : "2024-02-10" },
{ "score" : 85, "date" : "2024-01-15" },
{ "score" : 78, "date" : "2024-03-05" }
]
}
コードの例
$sort 更新修飾子を使用するコード例を表示するには、使用する言語のタブを選択します。
- Node.js
-
const { MongoClient } = require('mongodb');
async function updateDocument() {
const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
const db = client.db('test');
const collection = db.collection('students');
await collection.updateOne(
{ _id: 1 },
{
$push: {
quizzes: {
$each: [{ score: 78, date: "2024-03-05" }],
$sort: { score: -1 }
}
}
}
);
const updatedDocument = await collection.findOne({ _id: 1 });
console.log(updatedDocument);
await client.close();
}
updateDocument();
- Python
-
from pymongo import MongoClient
def update_document():
client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
db = client.test
collection = db.students
collection.update_one(
{'_id': 1},
{
'$push': {
'quizzes': {
'$each': [{'score': 78, 'date': '2024-03-05'}],
'$sort': {'score': -1}
}
}
}
)
updated_document = collection.find_one({'_id': 1})
print(updated_document)
client.close()
update_document()