简体   繁体   English

按 ID 查询 Firebase Firestore 文档

[英]Query Firebase Firestore documents by the ID

As I got from 'Cloud Firestore Data Model' guide "each document is identified by a name."正如我从“Cloud Firestore 数据模型”指南中得到的那样,“每个文档都由一个名称标识。” Is it possible to query a collection by that document identifier (which is the name or ID)?是否可以通过该文档标识符(即名称或 ID)查询集合?

For example, documents in the collection "Things" have IDs: 0, 1, 2 etc.:例如,集合“Things”中的文档具有 ID:0、1、2 等:

在此处输入图像描述

Is it possible to query documents which IDs are less than 100?是否可以查询ID小于100的文档?

You can query by documentId using the special sentinel FieldPath.documentId() , eg:您可以使用特殊FieldPath.documentId()按 documentId 查询,例如:

const querySnap = collection.where(firebase.firestore.FieldPath.documentId(), '<', '100').get();

But be aware that document IDs are strings and therefore this will include documents with ID '0' or '1', but not '2' since '2' > '100' lexicographically.但请注意,文档 ID 是字符串,因此这将包括 ID 为“0”或“1”的文档,但不包括“2”,因为字典上的“2”>“100”。

So if you want a numeric query, you'll need to write the document ID as a numeric field in the document and then do a normal query on it.因此,如果您需要数字查询,则需要将文档 ID 作为数字字段写入文档中,然后对其进行常规查询。

In python, you should use full documents names在 python 中,您应该使用完整的文档名称

from google.cloud import firestore
from google.cloud.firestore_v1.field_path import FieldPath

db = firestore.Client()
colRef = db.collection(u'docs')
filter = [db.document(u'docs/doc1'), db.collection(u'docs/doc3')]
query = colRef.where(FieldPath.document_id(), u'in', filter)

You can also try "filling" your ids so that '1' becomes '001', '2' becomes '002', and so on. 您也可以尝试“填充”您的ID,使'1'变为'001','2'变为'002',依此类推。 If you have no idea your total number of items it may not seem convenient but it should make your query work. 如果你不知道你的项目总数,它可能看起来不方便,但它应该使你的查询工作。

i've found this way 我发现了这种方式

constructor(private afs: AngularFirestore) { }

ngOnInit() {
  private thingsDoc: AngularFirestoreDocument<Item>;
  this.thingsDoc = this.afs.collection<any('Things').doc(INSERT_YOUR_ID);

  this.thingsDoc.valueChanges().subscribe((value: any) => {
   console.log('thing', value);
  });
}

I was struggling to find this for the Golang Firebase SDK but finally got it.我一直在努力为 Golang Firebase SDK 找到它,但最终得到了它。 Hope this helps somebody out there!希望这可以帮助那里的人!

package main
    
import (
  "context"
  "fmt"
  "log"

  "cloud.google.com/go/firestore"
  firebase "firebase.google.com/go/v4"
  "google.golang.org/api/option"
)

type (
  Car struct {
    ID    string
    Name  string  `firestore:"name"`
    Make  string  `firestore:"make"`
    Price float64 `firestore:"make"`
  }
)

func main() {
  ctx := context.Background()

  // Use a service account
  options := option.WithCredentialsFile("PATH/TO/SERVICE/FILE.json")

  // Set project id
  conf := &firebase.Config{ProjectID: "PROJECT_NAME"}

  // Initialize app
  app, err := firebase.NewApp(ctx, conf, options)
  if err != nil {
    log.Fatal(err)
  }

  // Get firestore client
  client, err := app.Firestore(ctx)
  if err != nil {
    log.Fatal(err)
  }
  defer client.Close()

  collectionRef := client.Collection("CAR_COLLECTION")
  
  // Create docment list of documents from "CAR_COLLECTION"
  var skipDocs []*firestore.DocumentRef
  idList := []string{"001", "002", "003"}
  for _, id := range idList {
    skipDocs = append(skipDocs, collectionRef.Doc(id))
  }

  // firestore.DocumentID == "__name__" 
  docs, err := collectionRef.Where(firestore.DocumentID, "not-in", skipDocs).Documents(ctx).GetAll()
  if err != nil {
    log.Fatal(err)
  }

  var carList []Car
  for _, doc := range docs {
    var car Car

    // Unmarshall item
    doc.DataTo(&car)
    car.ID = doc.Ref.ID

    // Add car to list
    carList = append(carList, car)
  }

  // Print car list
  fmt.Println(carList)
}

Yes you can query a document identified by an id like suggested in @Michael Lehenbaur's response . 是的,您可以查询由@Michael Lehenbaur的回复中建议的ID标识的文档。

I want to add as an aside that it is bad practice to have predictable sequential keys since they lend themselves to scalability issues. 我想补充说,由于它们适用于可扩展性问题,因此拥有可预测的顺序密钥是不好的做法。 You should use randomly generated keys to avoid hotspots in the database. 您应该使用随机生成的密钥来避免数据库中的热点。 For reference, see the firebase mailing list discussion 有关参考,请参阅firebase邮件列表讨论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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