猫鼬-仅按日期部分对日期排序,忽略时间 [英] Mongoose - sort Date by date part only, ignoring time
问题描述
我有一个用于以下模型的收藏集:
const VisitSchema = new mongoose.Schema({
priority: { type: Number, min: 1, max: 3, required: true },
datetime: { type: Date, required: true },
// some other information
});
我正在尝试对所有文档进行排序,以使比当前日期更近的访问显示在后面的访问之前,但是在一天之内,必须首先显示优先级较高的访问.
例如:考虑
A (17-08-2018 14:00:00, P3)
B (17-08-2018 15:00:00, P2)
C (18-08-2018 15:00:00, P1)
在对它进行排序时,所需的响应应该为[B, A, C]
,因为在17-08-2018
日,即使A
更早,并且C
具有比A
更早的优先级,B
也具有比A
更高的优先级. A
和B
,都在以后的一天.
我正在寻找一种方法,该方法首先按datetime
进行排序,但仅考虑日期部分并忽略时间,然后再按priority
进行排序.我目前的尝试完全考虑了datetime
,这给了我错误的排序方式:
Visit.find().sort('datetime priority')
编辑:我知道我可以使用Array.sort()
来做到这一点.问题是直接从mongoose
执行此操作,而不是先检索数据然后才进行排序.
您可以尝试在3.6以下的聚合中进行自定义排序.
使用 $dateFromParts
来计算日期而无需时间 $addFields
可以将计算所得的值保留为该文档后跟 $sort
在字段中排序.>
$project
,并排除掉排序字段以获得预期的输出.
db.col.aggregate([
{"$addFields":{
"date":{
"$dateFromParts":{
"year":{"$year":"$datetime"},
"month":{"$month":"$datetime"},
"day":{"$dayOfMonth":"$datetime"}
}
}
}},
{"$sort":{"date":-1,"priority":1}},
{"$project":{"date":0}}
])
I have a collection for the following model:
const VisitSchema = new mongoose.Schema({
priority: { type: Number, min: 1, max: 3, required: true },
datetime: { type: Date, required: true },
// some other information
});
I'm trying to sort all documents in a way that the Visits closer to current date are shown before the later ones, but within a day, the ones with higher priority must be shown first.
For example: consider
A (17-08-2018 14:00:00, P3)
B (17-08-2018 15:00:00, P2)
C (18-08-2018 15:00:00, P1)
when sorting this, the desired response should be [B, A, C]
, because on day 17-08-2018
, B
has higher priority over A
even though A
is earlier and even if C
has higher priority over both A
and B
, it is on a later day.
I'm looking for a way to sort firstly by datetime
, but consider only the Date part and ignoring the Time, and later by priority
. My current attempt considers the datetime
entirely, giving me the wrong sorting:
Visit.find().sort('datetime priority')
EDIT: I know I can do it using Array.sort()
. The question is upon doing it directly from mongoose
, instead of retrieving the data and only then sorting.
You can try below aggregation in 3.6 for custom sort.
Use $dateFromParts
to compute date without time in $addFields
to keep the computed value as the extra field in the document followed by $sort
sort on field.
$project
with exclusion to drop the sort field to get expected output.
db.col.aggregate([
{"$addFields":{
"date":{
"$dateFromParts":{
"year":{"$year":"$datetime"},
"month":{"$month":"$datetime"},
"day":{"$dayOfMonth":"$datetime"}
}
}
}},
{"$sort":{"date":-1,"priority":1}},
{"$project":{"date":0}}
])
这篇关于猫鼬-仅按日期部分对日期排序,忽略时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!