gpt4 book ai didi

MongoDB - 按单词排序

转载 作者:行者123 更新时间:2023-12-04 10:45:40 25 4
gpt4 key购买 nike

有如下数据。

{
"summary": "testing api1",
"UpdatedDate": {
"$date": "2018-12-30T00:00:00.000Z"
},
"status": "draft"
},
{
"summary": "testing api2",
"UpdatedDate": {
"$date": "2018-12-30T00:00:00.000Z"
},
"status": "published"
},
{
"summary": "testing api3",
"UpdatedDate": {
"$date": "2018-12-30T00:00:00.000Z"
},
"status": "delete"
}

我想根据“ 状态”进行排序
例如:如果我按状态排序“ 已发布 ”,那么我需要如下数据
{
"summary": "testing api2",
"UpdatedDate": {
"$date": "2018-12-31T00:00:00.000Z"
},
"status": "published"
},
{
"summary": "testing api1",
"UpdatedDate": {
"$date": "2018-12-30T00:00:00.000Z"
},
"status": "draft"
},
{
"summary": "testing api3",
"UpdatedDate": {
"$date": "2019-01-01T00:00:00.000Z"
},
"status": "delete"
}

在mongodb中可能吗?或任何类似的东西?

最佳答案

理想情况下,您会分配一个数值。但是您可以像使用聚合框架一样做到这一点。

类似这样的事情 $addFields $cond :

db.getCollection("yourcollection").aggregate([
{
$addFields: {
sortNum: {
$cond: [
{ $eq: ["$status", "published"] },
0,
{ $cond: [{ $eq: ["$status", "draft"] }, 1, 2] }
]
}
}
},

{
$sort: {
sortNum: 1
}
}
]);

$switch
db.collection.aggregate([{
$addFields: {
sortNum: {
$switch: {
branches: [
{
case: {
$eq: ["$status", "published"]
},
then: 1
},
{
case: {
$eq: ["$status", "delete"]
},
then: 2
},
{
case: {
$eq: ["$status", "draft"]
},
then: 3
}
],
default: 0
}
}
}
},
{
$sort: {
sortNum: 1
}
}]);

关于MongoDB - 按单词排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59719001/

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