mongodb - 在mongodb中根据字符串中的时间排序
问题描述
time(time_required)
如果我以这种格式保存,我该如何排序?
quiz_customer_record
{
"_id" : ObjectId("5f16eb4a5007bd5395c76ed9"),
"quiz_id" : "5f05bbd10cf3166085be68fc",
"user_id" : "5f06e0ddf718c04de30ea47f",
"name" : "ABC",
"time_required" : "0:6 Mins",
"questions_attempted" : 0,
"total_quiz_questions" : 1,
"attempt_date" : "2020-07-21T13:19:08.025Z"
},
{
"_id" : ObjectId("5f16eb5f5007bd5395c76edb"),
"quiz_id" : "5f05bbd10cf3166085be68fc",
"user_id" : "5f06e0ddf718c04de30ea47f",
"name" : "ABC",
"time_required" : "0:8 Mins",
"questions_attempted" : 0,
"total_quiz_questions" : 1,
"attempt_date" : "2020-07-21T13:19:29.377Z"
}
我想根据它对它进行排序,time_required
但它是字符串格式,格式为Mins:Seconds
. 是的,它非常混乱。但是我们有解决方案吗?我想为此使用 mongo 查询,因为记录太多,我有点需要使用限制(用于分页)。这就是为什么有必要使用 mongo 查询。
预期结果 - 排序类型 - 降序()
{
"_id" : ObjectId("5f16eb5f5007bd5395c76edb"),
"quiz_id" : "5f05bbd10cf3166085be68fc",
"user_id" : "5f06e0ddf718c04de30ea47f",
"name" : "ABC",
"time_required" : "0:8 Mins",
"questions_attempted" : 0,
"total_quiz_questions" : 1,
"attempt_date" : "2020-07-21T13:19:29.377Z"
},
{
"_id" : ObjectId("5f16eb4a5007bd5395c76ed9"),
"quiz_id" : "5f05bbd10cf3166085be68fc",
"user_id" : "5f06e0ddf718c04de30ea47f",
"name" : "ABC",
"time_required" : "0:6 Mins",
"questions_attempted" : 0,
"total_quiz_questions" : 1,
"attempt_date" : "2020-07-21T13:19:08.025Z"
}
我正在使用的查询是
db.quiz_customer_record.aggregate([{ $match: { quiz_id:quiz_id}},
{
$sort: { attempt_date: -1 }
},
{
$group: {
_id: "$user_id",
result1: { $first: "$attempt_date" },
quiz_id: { $first: "$quiz_id" },
time_required: { $first: "$time_required" },
o_id: { $first: "$_id" }
}
},
{
$project: {
_id: "$o_id",
user_id: "$_id",
quiz_id:"$quiz_id",
time_required:"$time_required",
result1: 1
}
}
]).sort({time_required:-1})
解决方案
mongo版本低于4.2的答案
$set
在 4.2 版本中添加。对于早期版本$addFields
可以使用。
db.collection.aggregate([
{
"$addFields": {
"time_required_split": {
$substr: [
"$time_required",
0,
3
]
}
}
},
{
"$addFields": {
"time_required_split": {
$split: [
"$time_required_split",
":"
]
}
}
},
{
"$addFields": {
"time_seconds": {
$sum: [
{
"$multiply": [
{
$toInt: {
$arrayElemAt: [
"$time_required_split",
0
]
}
},
60
]
},
{
$toInt: {
$arrayElemAt: [
"$time_required_split",
1
]
}
}
]
}
}
},
{
"$sort": {
time_seconds: -1
}
},
{
"$project": {
"time_required_split": 0,
"time_seconds": 0
}
}
])
推荐阅读
- php - PHP 从预填充的下拉菜单中插入表单数据
- r - 我错过了一些更漂亮的方式吗?使用 NHSDataDictionaRy 中的 tibble 重构 tibble
- python - Python KIvy 旋转矩形在调整大小时移动
- r - 字符向量上的下标和上标
- javascript - 使用 Javascript 搜索过滤器
- google-sheets - 在 Google 表格阅读模式下启用下拉列表
- openstack - 使用 kolla-ansible 时如何固定 openstack 容器版本?
- vba - 如何在没有 OAuth 2.0 客户端 ID 的情况下使用 API 密钥从 VBA 调用 Google Apps 脚本?
- java - 将试听信息从一组嵌入对象迁移到一组实体
- javascript - this.$refs 使用 Vue 3 选项 API 为空