本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$sort
与运算符一起使用时,u $sort pdate 修饰$push符会对数组元素进行排序。它根据指定的字段值或元素本身按升序或降序排列数组元素。
参数
-
field:要修改的数组字段。
-
order:1用于升序或-1降序。
示例(MongoDB 外壳)
以下示例演示了使用$sort修饰符wit $push h来添加新的测验分数并按降序对它们进行排序。
创建示例文档
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()