[英]JS mongoDB sort by previousItem property (parent-child relationship)
我有一个项目集合,其中的文档具有重要的顺序,并且顺序可能会更改(即,创建时间或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. index属性是一个字符串,以便允许多于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})的输出
产生预期的结果。
是否将索引添加到记录集中,然后在查询时可以使结果集按该索引排序在您的情况下不起作用?
https://docs.mongodb.org/v3.0/tutorial/sort-results-with-indexes/
编辑更新:
您可以使用索引的细分,例如:
在indexA = 2和indexB = 3的元素之间插入,生成insertIndex =(2 + 3)/ 2 = 2.5
但是,在Javascript中,您需要使用最大为17个小数的浮点数,与MongoDB double相同。 您将需要考虑到这一点,如果发生了舍入操作,例如,如果insertIndex = indexA或= indexB,那么您将达到限制,需要调用一个函数来更新数据库并循环所有元素以使用例如整数来更新其索引。 第一次执行此操作后,它很可能不会经常触发,并且随着时间的推移会越来越少触发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.