gpt4 book ai didi

javascript - 如何在Mongodb中使用条件语句进行排序

转载 作者:行者123 更新时间:2023-12-05 04:33:56 25 4
gpt4 key购买 nike

举个例子,假设我的收藏是这样的,

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"
},
]

我要这里,提供的元素降序排在第一位,它不应该过期,然后剩余的项目应该进来降序所以结果是这样的

   [


{
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,

},


]

最佳答案

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

关于javascript - 如何在Mongodb中使用条件语句进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71276662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com