'Getting biggest document from a collection in the last 24 hours in Firestore
I have a collection of trades in my Firestore database. The trades have the following relevant data that I need in the query:
time: 1589535935410 (milliseconds)
tradeValue: 12343.017
isBuyerMaker: true || false
I need to run a query that gets the biggest TradeValue (one in isBuyerMaker true and also in false) in the last 24 hours. How can I achieve this through Firestore queries?
I tried running this query:
const biggestBuyQuery = firebase
.firestore()
.collection("cex-trades")
.orderBy("time", "desc")
.where("isBuyerMaker", "==", true)
.where("time", ">", seconds24h())
.orderBy("tradeValue", "desc")
.limit(1);
This does get the documents from the last 24 hours but since it is being ordered by time, I do not get the biggest tradeValue
Solution 1:[1]
From the tags I'm going to assume you're working with the JS firestore API.
Edit: I've added workaround that should work for this:
let query = collection
.where("isBuyerMaker", "==", /* true / false */)
.where("time", ">", /* now.milliseconds - (24*60*60*1000) */)
.where("tradeValue", ">=", 0) // New workaround
.orderBy("tradeValue", "desc")
.limit(1)
.get()
I'd run a compound query with a few where clauses:
let query = collection
.where("isBuyerMaker", "==", /* true / false */)
.where("time", ">", /* now.milliseconds - (24*60*60*1000) */)
.orderBy("tradeValue", "desc")
.limit(1)
.get()
and collect the 0th document from the promise when it resolved
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
