简体   繁体   中英

How to query firebase firestore an array of map data?

how do I query or find the color inside a collection, in firebase firestore?

How do I find green?

let snapshot = await Firestore.collection("products")
            .where("products.color", "=" , "green")
            .get()

color: [
  {
   color: "green"
   id: "9ry4G5"
  },
  {
   color: "red"
   id: "I9gt54"
  },
  {
   color: "blue"
   id: "lD4Y78"
  },
]

To query for an item in an array, you must include the entire item. You can't search for a partial element in an array.

In addition, you'll need to use the array-contains operator, so that the database knows it needs to search for a matching item inside in the array, instead of matching the entire array.

To find the color green, you'd need to:

Firestore.collection("products")
         .where("products.color", "array-contains" , { color: "green", id: "9ry4G5" })

This assumed that the array is called color and is in a (map) field called `products. If the array field is at the top level of the document, it'd be

Firestore.collection("products")
         .where("color", "array-contains" , { color: "green", id: "9ry4G5" })

If you don't know the ID, you may want to consider adding an additional field to your documents that holds just the color names (say color_names ), and then use that to query on:

Firestore.collection("products")
         .where("color_names", "array-contains" , "green")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM