javascript - JS mongoDB 按 previousItem 属性排序(父子关系)

标签 javascript mongodb sorting

我有一个项目集合,其中的文档具有重要的顺序,并且可能会发生变化(即创建时间或 ID 不能用于排序)。

我认为添加 previous/nextItem 属性可能是一个解决方案

{
  id: 1,
  name: "itemC",
  previousItem : 2,
  nextItem : 0
}

{
  id: 0
  name: "itemB", 
  previousItem : 1,
  nextItem : null
}

{
  id: 2,
  name: "itemA",
  previousItem : null,
  nextItem : 1
}

我想根据遍历 previousItem 属性的排序参数检索记录。

以上集合应返回为:

{
  id: 2,
  name: "itemA",
  previousItem : null,
  nextItem : 1
}

{
  id: 1,
  name: "itemC",
  previousItem : 2,
  nextItem : 0
}

{
  id: 0
  name: "itemB", 
  previousItem : 1,
  nextItem : null
}

最佳答案

下面是排序索引的基本假设: 1. 索引属性是一个字符串,以便允许超过 17 位数字。 2.仅使用相邻项的最后一位来计算新索引,以避免计算超过17位。算法(以下值均为字符串):

indices:
I1
I2
I3

add item between 1 and 2 --> 
   is there an integer between the two values?
   yes --> use it as the new index
   no --> use the lower index and append 05, add 00 to lower index

eval (1,2) --> no

I100
I105
I2
I3

add an item between 100 and 105
eval(100,105) --> yes

I100
I102
I105
I2
I3

add an item between 100 and 102
eval(100,102) --> yes

I100
I101
I102
I105
I2
I3

add an item between 100 and 101
eval(100,101) --> no

I100
I1005
I101
I102
I105
I2
I3

and so on.

输出为 db.getCollection('items').find({}).sort({index: 1})

产生预期的结果。

关于javascript - JS mongoDB 按 previousItem 属性排序(父子关系),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34746088/

相关文章:

javascript - "Term"特性中传入的默认 "jquery UI autocomplete"名称是否可以更改?

javascript - 在 handlebars 模板中显示 hasMany ember 关系中的第一项

arrays - 在 mongoDB 中使用数组索引获取数组元素

linux - 如何使用内置的 "sort"程序同时按两个字段(一个数字,一个字符串)排序?

java - 改变java排序算法

javascript - facebook 的 all.js 太大了,有替代方案吗

mongodb - meteor 批量更新

mongodb - 如何在子属性上使用 $setIsSubset (或其他集合操作)

algorithm - 选择算法运行时

javascript - 我可以从 jquery 中的变量调用 ID 元素 HTML