Mongo按两个字段中的任何一个进行排序

huangapple go评论136阅读模式
英文:

Mongo sort by either of 2 fields

问题

我有一些文件,其中foo字段始终嵌套在xy中,而不是同时出现。

我想要按此字段排序并获取结果。

如果可以使用find().sort()来实现,那将很好,但如果需要使用aggregate(),也希望得到相关答案。

英文:

I have documents where the foo field is always nested in x or y and not both.

{
    "_id": ObjectId("5a6eb97b2937803b14255180"),
    "x": {
        "foo": 42
    },
    "y": { }
},
{
    "_id": ObjectId("5a6eb97b2937803b14255181"),
    "x": { },
    "y": {
        "foo": 24
    }
}

I want to sort by it and get

{
    "_id": ObjectId("5a6eb97b2937803b14255181"),
    "x": { },
    "y": {
        "foo": 24
    }
},
{
    "_id": ObjectId("5a6eb97b2937803b14255180"),
    "x": {
        "foo": 42
    },
    "y": { }
}

It would be great if I can do it with find().sort() and not aggregate(), but an aggregate() answer would be appriciated too.

答案1

得分: 1

使用$ifNull创建一个排序键,如果x.foo不存在,则回退到y.foo,然后根据排序键进行排序。

db.collection.aggregate([
  {
    "$set": {
      "sortKey": {
        "$ifNull": [
          "$x.foo",
          "$y.foo"
        ]
      }
    }
  },
  {
    $sort: {
      sortKey: 1
    }
  },
  {
    "$unset": "sortKey"
  }
])

Mongo Playground

英文:

Create a sort key with $ifNull to fall back into y.foo if x.foo is not present then sort on the sort key.

db.collection.aggregate([
  {
    "$set": {
      "sortKey": {
        "$ifNull": [
          "$x.foo",
          "$y.foo"
        ]
      }
    }
  },
  {
    $sort: {
      sortKey: 1
    }
  },
  {
    "$unset": "sortKey"
  }
])

Mongo Playground


Side note: It might be better if you can preprocess your documents and materialized a single sort key. You can then index the consolidated sort key to gain performance boost and simpler queries.

huangapple
  • 本文由 发表于 2023年3月7日 00:58:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653695.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定