gpt4 book ai didi

arrays - Firestore 数组中的排序顺序

转载 作者:行者123 更新时间:2023-12-04 04:29:59 25 4
gpt4 key购买 nike

我试图更多地了解 Firebase 中的数组。目前,我将 map 存储在数组中,其中 map 内的字段之一是 position我可以在我的移动应用程序中使用它在检索时对数组进行排序并按 position 的顺序显示结果.

docs on Firebase说:

Arrays are sorted by elements. If elements are equal, the arrays are sorted by length.

For example, [1, 2, 3] < [1, 2, 3, 1] < [2].



然后还有一个部分描述了 map 是如何排序的:

Key ordering is always sorted. For example, if you write {c: "foo", a: "bar", b: "qux"} the map is sorted by key and saved as {a: "foo", b: "bar", c: "qux"}.

Map fields are sorted by key and compared by key-value pairs, first comparing the keys and then the values. If the first key-value pairs are equal, the next key-value pairs are compared, and so on. If two maps start with the same key-value pairs, then map length is considered. For example, the following maps are in ascending order:

{a: "aaa", b: "baz"}
{a: "foo", b: "bar"}
{a: "foo", b: "bar", c: "qux"}
{a: "foo", b: "baz"}
{b: "aaa", c: "baz"}
{c: "aaa"}


但是后来我在 Firestore 中尝试了这个:我在上面的例子中混淆了 map 的顺序,并将它们存储在一个数组中:
data= [{"c": "aaa"}, {"a": "aaa", "b": "baz"}, {"a": "foo", "b": "baz"}, {"b": "aaa", "c": "baz"}, {"a": "foo", "b": "bar", "c": "qux"}, {"a": "foo", "b": "bar"}]

并且在插入 Firestore 文档时,数组没有得到排序!虽然键本身确实在单个 Map 中排序,但数组中的元素保持相同的顺序。

那么当元素是 Map 时,数组中的排序是否有效?这是我在 Firestore 中存储的示例:
{
"car_collection": {
"models": {
data: [
{
"model": "Honda",
"color": "black",
"position": 0
},
{
"model": "Hyundai",
"color": "red",
"position": 1
},
{
"model": "Chevrolet",
"color": "yellow"
"position": 2
}
]
}
}
}

我正在存储一个名为“位置”的附加字段,并且每次检索时 map 的顺序都保持不变。想知道我是否需要存储这个字段,或者数据将按照我存储的顺序排序。

最佳答案

向 Google 提交了一张票以改进 Array 类型的文档,我认为通过一些烟雾测试可以看出它是有帮助和准确的。
https://firebase.google.com/docs/firestore/manage-data/data-types
在此处复制粘贴当前版本:

An array cannot contain another array value as one of its elements.

Within an array, elements maintain the position assigned to them. When sorting two or more arrays, arrays are ordered based on their element values.

When comparing two arrays, the first elements of each array are compared. If the first elements are equal, then the second elements are compared and so on until a difference is found. If an array runs out of elements to compare but is equal up to that point, then the shorter array is ordered before the longer array.

For example, [1, 2, 3] < [1, 2, 3, 1] < [2]. The array [2] has the greatest first element value. The array [1, 2, 3] has elements equal to the first three elements of [1, 2, 3, 1] but is shorter in length.


因此,您似乎可以放心地期望在 Firestore 中维护元素的顺序,同时了解添加/删除的效果。

关于arrays - Firestore 数组中的排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54612101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com