Reputation: 1916
As I got from 'Cloud Firestore Data Model' guide "each document is identified by a name." Is it possible to query a collection by that document identifier (which is the name or ID)?
For example, documents in the collection "Things" have IDs: 0, 1, 2 etc.:
Is it possible to query documents which IDs are less than 100?
Upvotes: 25
Views: 26659
Reputation: 766
I was struggling to find this for the Golang Firebase SDK but finally got it. 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)
}
Upvotes: 1
Reputation: 614
In python, you should use full documents names
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)
Upvotes: 18
Reputation: 16309
You can query by documentId using the special sentinel FieldPath.documentId()
, e.g.:
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.
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.
Upvotes: 45