【问题标题】:array_contains query on Objectsarray_contains 查询对象
【发布时间】:2018-09-22 18:22:15
【问题描述】:

如果我在集合的每个文档中都有一个名为array_field字段,它由类型为object 的元素组成,我可以查询一个对象中的特定字段

- collection

  - document1
    - array_field
      0: { type: tree, age: 143 }
      1: { type: sunflower, age: 1 }
      2: { type: fungus, age: 3 }

  - document2
    - array_field
      0: { type: plane, age: 38 }
      1: { type: plant, age: 2 }
      2: { type: fungus, age: 1 }

是否有可能查询 在其 array_field 中具有类型为 fungus 的对象的每个文档?

如果这不可能,有没有办法通过指定确切的object来查询文档?
我不知道如何编写查询:.where('array_field', 'array_contains', /*how do I define this object*/)。会不会只是一个像这样的 JSON 对象:{type: fungus, age: 2}

我要实现的查询如下:

where('array_field', 'array_contains', 'type:fungus')

这将返回 document1document2,但我找不到任何关于此类情况的语法提示。

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    这在您当前的数据结构中是不可能的。 array_contains 仅在匹配数组元素的整个内容时才有效,而不仅仅是特定的对象字段。

    相反,您可以重组数据以使用具有唯一类型和布尔值的对象,这样您就可以查询types.fungus == true 之类的内容:

    document
        types {
            fungus: true
            plant: true
        }
    

    在 nosql 数据库中复制数据以适应您需要执行的特定查询是很常见的。

    【讨论】:

      猜你喜欢
      • 2019-02-02
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多