我有一个项目集合,其中的文档具有重要的顺序,并且可能会发生变化(即创建时间或 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/