如何对字典键进行排序并在 MongoDb 中选择第一个键?

问题描述

我正在按照 the docs 中的描述运行以下查询

db.getCollection('things')
  .find(
    { _id: UUID("...") },{ _id: 0,history: 1 }
  )

生成一个元素,当在 GUI 中展开时,显示字典历史。当我展开它时,我会看到内容:一堆键和相关值。

现在,我想按字母顺序对键进行排序并选择 n 个第一个。请注意,它不是一个数组,而是一个存储的字典。此外,如果我可以将结构展平并弹出我的历史作为返回文档的头部(根?),那就太好了。

我理解它是关于投影和切片的。但是,尽管进行了多次尝试,但我一无所获。我收到语法错误或完整的元素列表。比较菜鸟,我担心我需要一些关于如何诊断我的问题的指示。

根据评论,我尝试了 aggregate$sort。遗憾的是,我似乎只是对当前输出进行排序(由于匹配条件而产生单个文档)。我想访问 history 中的元素。

db.getCollection('things')
  .aggregate([
    { $match: { _id: UUID("...") } },{ $sort: { history: 1 } }
  ])

我感觉我应该使用投影来提取位于 history 下的元素列表,但使用以下内容没有成功。

db.getCollection('things')
  .aggregate([
    { $match: { _id: UUID("...") } },{ $project: { history: 1,_id: 0 } }
  ])

解决方法

仅按字母顺序对对象属性进行排序是一个漫长的过程,

  • $objectToArrayhistory 对象转换为键值格式的数组
  • $unwind 解构上面生成的数组
  • $sorthistory 键升序(1 = 升序,-1 = 降序)
  • $group by _id 并重构 history 键值数组
  • $slice 要从字典顶部获取您的属性数,我输入了 1
  • $arrayToObject 返回将键值数组转换为对象格式
db.getCollection('things').aggregate([
  { $match: { _id: UUID("...") } },{ $project: { history: { $objectToArray: "$history" } } },{ $unwind: "$history" },{ $sort: { "history.k": 1 } },{
    $group: {
      _id: "$_id",history: { $push: "$history" }
    }
  },{ 
    $project: { 
      history: { 
        $arrayToObject: { $slice: ["$history",1] } 
      } 
    } 
  }
])

Playground


还有另一种选择,但根据 MongoDB,它不能保证这会重现准确的结果,

  • $objectToArrayhistory 对象转换为键值格式的数组
  • $setUnion 基本上这个运算符将从数组中获取唯一元素,但根据经验,它会按键升序对元素进行排序,因此根据 MongoDB 无法保证。
  • $slice 要从字典顶部获取您的属性数,我输入了 1
  • $arrayToObject 返回将键值数组转换为对象格式
db.getCollection('things').aggregate([
  { $match: { _id: UUID("...") } },{
    $project: {
      history: {
        $arrayToObject: {
          $slice: [
            { $setUnion: { $objectToArray: "$history" } },1
          ]
        }
      }
    }
  }
])

Playground