MongoDB - 按键值数组中的值排序

问题描述 投票:0回答:1

我有这个数据结构

{
  "_id": "123456789abc",
  ...
  "information": [
    {
      "key": "email",
      "value": "[email protected]"
    },
    {
      "key": "company",
      "value": "ABC"
    },
    {
      "key": "registrationDate",
      "value": {
        "$date": "2023-11-10T20:00:49.000Z"
      }
    },
    {
      "key": "expiryDate",
      "value": {
        "$date": "2024-11-10T20:02:11.000Z"
      }
    }
  ]
}

我必须按“information.key”字段中的值对查询结果进行排序

例如:

information.key = email: information.value 1
information.key = registrationDate: information.value -1

我该怎么做?

非常感谢您的帮助

json mongodb sorting
1个回答
0
投票

使用

$arrayToObject
将数组转换为对象,然后对新创建的对象的字段进行排序。

db.collection.aggregate([
  {
    "$set": {
      "infoObject": {
        "$arrayToObject": {
          "$map": {
            "input": "$information",
            "as": "i",
            "in": {
              k: "$$i.key",
              v: "$$i.value"
            }
          }
        }
      }
    }
  },
  {
    "$sort": {
      "infoObject.email": 1,
      "infoObject.registrationDate": -1
    }
  },
  {
    "$unset": "infoObject"
  }
])

蒙戈游乐场

© www.soinside.com 2019 - 2024. All rights reserved.