Mongodb条件排序 [英] Mongodb conditional sort
问题描述
我想为sort
子句添加一个字段,仅适用于一天前创建的那些文档.
假设在我的收藏集mycollection
中,我的文档有一个字段publishDate
和其他一些字段,下面是我的查询:
I want to add a field to the sort
clause, for only those documents that created one day ago.
Suppose in my collection mycollection
my documents have a field publishDate
, and some other fields, and following is my query:
db.getCollection('mycollection').aggregate([
{
"$match": {
"expireDate": {
"$gte": ISODate("2019-03-14T00:00:00.000Z")
},
"publishDate": {
"$lt": ISODate("2019-03-15T00:00:00.000Z")
},
"isPublished": true,
"isDrafted": false,
"deletedAt": {
"$eq": null
},
"deleted": false,
"blocked": {
"$exists": false
}
}
},
{
"$sort": {
"isFeatured": -1, // What I want is to add this field in sort clause by condition, when publishDate is yesterday, otherwise ignore it
"refreshes.refreshAt": -1,
"publishDate": -1,
"_id": -1
}
},
{
"$skip": 0
},
{
"$limit": 12
},
{
"$project": {
"position": 1
}
}])
推荐答案
创建一个虚拟字段,该字段表示应显示在列表顶部的条目的值,然后根据该字段对条目进行排序.您可以使用 $addFields
和
Create a virtual field which represents a value for the entries that should be shown on top of the list, then sort entries based on that field. You can use $addFields
and $cond
operators to accomplish it.
实现将是这样的:
// ...
{
"$addFields": {
"isFeaturedSort": {
"$cond": {
"if": {
"$and": {
"publishDate": {
"$gte": ISODate("2019-03-14T00:00:00.000Z"),
},
"$eq": ["isFeatured", true],
},
},
"then": 1,
"else": 0,
},
},
},
},
{
"$sort": {
"isFeaturedSort": -1, // changed
"refreshes.refreshAt": -1,
"publishDate": -1,
"_id": -1,
},
},
// ...
请注意,$addField
仅在MongoDB 3.4及更高版本中有效.
摘录代码也可能包含错误.
Please notice that $addField
only work in MongoDB 3.4 and further.
also the snippets code may contain errors.
这篇关于Mongodb条件排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!