简体   繁体   中英

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

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

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