MongoDB - 按单词排序
·
问题:MongoDB - 按单词排序
有如下数据。
{
"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"
}
我想基于“status”进行排序例如:如果我已经按状态“published”进行排序,那么我需要如下数据
{
"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
}
}]);
更多推荐
所有评论(0)