mongodb 聚合:如果满足条件则排序,否则 return 文档原样

mongodb aggregation: sort if condition is satisfied else return document as it is

我想编写一个聚合管道,如果条件满足,我想在其中进行排序。如果不满足条件,那么我只想 return 按原样处理文件。如何继续下去? 我正在检查 has_presence 字段以决定是否根据名称字段对文档进行排序的示例文档(每个文档将始终有一个 has_presence 字段):

案例 1:

Input:
    {
    "name": "microsoft",
    "has_presence": true
    },
    {
    "name": "google",
    "has_presence": true
    }
Output:
    {
    "name": "google",
    "has_presence": true
    },
    {
    "name": "microsoft",
    "has_presence": true
    }
Explanation: has_presence is true, so sorted the output by name.

案例 2:

Input:
    {
    "name": "microsoft",
    "has_presence": false
    },
    {
    "name": "google",
    "has_presence": false
    }
Output:
    {
    "name": "microsoft",
    "has_presence": false
    },
    {
    "name": "google",
    "has_presence": false
    }
Explanation: has_presence is false, so kept the order as it is in output.

这是我的例子:https://mongoplayground.net/p/5p7HOws9l5Q

db.collection.aggregate([
  {
    "$project": {
      name: 1,
      has_presence: 1,
      sort: {
        "$cond": {
          "if": "$has_presence",
          "then": "$name",
          "else": "_id"
        }
      }
    }
  },
  {
    $sort: {
      sort: 1
    }
  }
])