英文:
How to use conditional statement for sort in Mongodb
问题
让我用一个例子来说明,假设我的集合是这样的:
products = [
{
id: 1,
name: "a",
offer: true,
expiryDate: "23-03-2022"
},
{
id: 2,
name: "b",
offer: false, //没有优惠
},
{
id: 3,
name: "c",
offer: true,
expiryDate: "01-01-2021" //已过期
},
{
id: 4,
name: "d",
offer: true,
expiryDate: "01-06-2022"
},
]
我想要的结果是,优惠的商品首先按降序排列,然后是未过期的商品按降序排列,最后是剩下的商品,所以结果应该是这样的:
[
{
id: 4,
name: "d",
offer: true,
expiryDate: "01-06-2022"
},
{
id: 1,
name: "a",
offer: true,
expiryDate: "23-03-2022"
},
{
id: 3,
name: "c",
offer: true,
expiryDate: "01-01-2021"
},
{
id: 2,
name: "b",
offer: false,
},
]
英文:
let me illustrate with an example,
suppose my collection is like this,
products = [
{
id: 1,
name: "a",
offer: true,
expiryDate: "23-03-2022"
},
{
id: 2,
name: "b",
offer: false,//no offer
},
{
id: 3,
name: "c",
offer: true,
expiryDate: "01-01-2021"//already expired
},
{
id: 4,
name: "d",
offer: true,
expiryDate: "01-06-2022"
},
]
I want here, the offered items comes first in descending order,
it should not expire and then the remaining item should come in
descending order so result would be like this
[
{
id: 4,
name: "d",
offer: true,
expiryDate: "01-06-2022"
},
{
id: 1,
name: "a",
offer: true,
expiryDate: "23-03-2022"
},
{
id: 3,
name: "c",
offer: true,
expiryDate: "01-01-2021"
},
{
id: 2,
name: "b",
offer: false,
},
]
答案1
得分: 2
db.collection.aggregate([
{
"$match": {}
},
{
"$set": {
"offer": {
"$cond": {
"if": {
"$lt": [
{
"$toDate": "$expiryDate"
},
"$$NOW"
]
},
"then": false,
"else": true
}
},
"expiryDate": {
"$toDate": "$expiryDate"
}
}
},
{
"$sort": {
"expiryDate": -1,
"offer": -1
}
}
])
[mongoplayground][1]
<details>
<summary>英文:</summary>
db.collection.aggregate([
{
"$match": {}
},
{
"$set": {
"offer": {
"$cond": {
"if": {
"$lt": [
{
"$toDate": "$expiryDate"
},
"$$NOW"
]
},
"then": false,
"else": true
}
},
"expiryDate": {
"$toDate": "$expiryDate"
}
}
},
{
"$sort": {
"expiryDate": -1,
"offer": -1
}
}
])
[mongoplayground][1]
[1]: https://mongoplayground.net/p/ZOJwpGCWjXJ
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论