mongo 根据其他字段的存在和排名在查询结果中设置新字段

mongo set new field in query results based on existence and rank of other fields

集合中的每个文档可能有 none/some/all 个字段,共 val1val2val3 个字段。我想查询 returns 结果,在其投影中设置一个字段 top_val,它只是 val1 的值,或者如果不存在,则va2,或者如果不存在,val3。 在伪代码中,类似于:

collection.find({ <condition> }, { "top_val": { "$val1" or "$val2" or "$val3" } )

您可以使用 $ifNull:

db.collection.aggregate([
  {
    "$project": {
      _id: 0,
      "top_val": {
        "$ifNull": [
          "$valA",
          {
            "$ifNull": [
              "$valB",
              "$valC"
            ]
          }
        ]
      }
    }
  }
])

如你所见here