# Querying the database
So far we have used references to documents and collections and feed them to Vuexfire to get a in-sync local version of them but you can also pass queries. This is pretty much transparent from Vuexfire perspective but here are some examples that you may find useful. If you need to check further, check Firebase documentation as there isn't any filtering or sorting feature in Vuexfire, it all comes from Firebase.
# One time read
If you don't care about having the data updated in real time whenever you modify or when you need to fetch some data that is only used once, you can use the native Firebase JS SDK, that's right, you don't need Vuexfire at all for that:
// retrieve a collection
db.collection('documents')
.get()
.then(querySnapshot => {
const documents = querySnapshot.docs.map(doc => doc.data())
// do something with documents
})
// retrieve a document
db.collection('documents')
.doc(documentId)
.get()
.then(snapshot => {
const document = snapshot.data()
// do something with document
})
To go further, check Firebase documentation:
# Sorting
RTDB and Firestore do not include the same set of features regarding sorting but here is a basic example of sorting a collection of documents
by the date of creation stored as createdAt
:
{
// omitting the rest of store options for simplicity reasons
actions: {
bindDocuments: firestoreAction(({ bindFirestoreRef }) => {
return bindFirestoreRef(
'documents',
db.collection('documents').orderBy('createdAt', 'desc')
)
})
}
}
To go further, check Firebase documentation:
- RTDB: Sorting and filtering data (opens new window)
- Order and limit data with Cloud Firestore (opens new window)
# Filtering
Firestore has many more features regarding filtering than RTDB but here is a basic filtering using one field with both databases:
// only get documents with more than 200 words
// the orderBy is optional
db.collection('documents')
.where('wordCount', '>', 200)
.orderBy('wordCount')
To go further, check Firebase documentation:
- RTDB: Sorting and filtering data (opens new window) and
equalTo
reference (opens new window). You should also checkstartAt
andendAt
in the same page. - Perform simple and compound queries in Cloud Firestore (opens new window)