Firestore 数组中的排序顺序

use*_*585 7 arrays types firebase google-cloud-firestore

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

Firebase 上文档说:

数组按元素排序。如果元素相等,则数组按长度排序。

例如,[1, 2, 3]< [1, 2, 3, 1]< [2]

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

键排序总是排序的。例如,如果您编写{c: "foo", a: "bar", b: "qux"}的地图按键排序并保存为{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"}
Run Code Online (Sandbox Code Playgroud)

But then I tried this in Firestore: I jumbled up the order of the maps in the above example, and stored them in an array:

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"}]
Run Code Online (Sandbox Code Playgroud)

And upon inserting into a Firestore document, the array did not get sorted! While the keys themselves do get sorted within a single Map, the elements in the array stay in the same order.

So does sorting in arrays even work when elements are Maps? Here's an example of what I'm storing in Firestore:

{
    "car_collection": {
        "models": {
            data: [
                {
                    "model": "Honda",
                    "color": "black",
                    "position": 0
                },
                {
                    "model": "Hyundai",
                    "color": "red",
                    "position": 1
                },
                {
                    "model": "Chevrolet",
                    "color": "yellow"
                    "position": 2
                }
            ]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

I'm storing an additional field called "position", and the order of maps stays the same on every retrieval. Wondering if I even need to store this field, or data will be sorted in the order that I store it in.

use*_*585 7

向 Google 提交了一张票以改进 Array 类型的文档,我认为通过一些烟雾测试可以看出它是有帮助和准确的。

https://firebase.google.com/docs/firestore/manage-data/data-types

在此处复制粘贴当前版本:

数组不能包含另一个数组值作为其元素之一。

在数组中,元素保持分配给它们的位置。对两个或多个数组进行排序时,数组将根据其元素值进行排序。

比较两个数组时,比较每个数组的第一个元素。如果第一个元素相等,则比较第二个元素,依此类推,直到找到差异为止。如果数组用完要比较的元素但在该点之前相等,则较短的数组排在较长的数组之前。

例如,[1, 2, 3] < [1, 2, 3, 1] < [2]。该数组[2]具有最大的第一个元素值。该数组的[1, 2, 3]元素等于 的前三个元素,[1, 2, 3, 1]但长度较短。

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