【问题标题】:Mongodb Aggregate with natural order具有自然顺序的Mongodb聚合
【发布时间】:2020-05-13 23:28:27
【问题描述】:

我正在寻找一种方法来查询数据库以获取集合中最后保存的条目。 我有一个函数可以将文档保存到集合中,这就是我保存的集合的样子。

{
  "_id": {
    "$oid": "5ebbf2b4586b4946226e2c88"
  },
  "name": "Stept_1",
  "description": "",
  "coordinates": {
    "pose": {
      "$numberInt": "0"
    },
    "x": {
      "$numberDouble": "-9.760518723445719"
    },
    "y": {
      "$numberDouble": "-3.4586615766853854"
    },
    "z": {
      "$numberInt": "0"
    }
  },
  "depth": {
    "$numberInt": "1"
  },
  "_neighbours": [],
  "optional": {},
  "__v": {
    "$Reference": "1111111"
  }
}

每个文档都以升序保存名称,例如name:Step_1, Step_2 etc。 我尝试使用聚合方法获取最后保存的文档,例如

db.collection.aggregate([
      { $sort: { name: -1 } },
      { $group: { _id: "$Reference", name: { $first: "$name" } } }
    ])

这会按升序返回数据,直到name:Step_10,即“Step_1,2,3,...”,但在name:Step_1o 之后一次,如果我重新启动应用程序并再次开始获取最后保存的文档,则升序索引返回到name:Step_9,然后导致一些文档的一些重复条目。我正在寻找的是它在获取这些文档时应该始终遵循自然顺序(即 Step_1,2,3,..11,12,13 等)。 提前致谢。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以使用collation 指定numericOrdering,如下所示:

    db.collection.aggregate([
          { $sort: { name: -1 } },
          { $group: { _id: "$Reference", name: { $first: "$name" } } }
        ], 
        { collation : { 
            locale: "en_US", 
            numericOrdering: true 
        }} 
    )
    

    来自 mongo 文档:

    numericOrdering 布尔值 可选的。确定是将数字字符串作为数字还是作为字符串进行比较的标志。

    如果为真,则比较为数字;即“10”大于“2”。

    如果为假,则作为字符串进行比较;即“10”小于“2”。

    默认为假。

    【讨论】:

    • 感谢您的快速回复。它工作:) 也感谢您的编辑建议。
    猜你喜欢
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多