#query by date

4 messages · Page 1 of 1 (latest)

raw briar
#

can i query by a date and if so, can i order by date?

lethal skyBOT
#

Hi @raw briar. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, you can query by date in Convex and order the results by date. In Convex, dates are typically stored as timestamps (either using JavaScript's Date.now() or as ISO strings).

Querying by Date

When querying by date, you can use the index system to efficiently filter your data. For example, if you have a field with a timestamp, you can create an index on that field and then use comparison operators like .gt(), .lt(), .gte(), or .lte() to filter by date ranges:

const results = await ctx.db
  .query("messages")
  .withIndex("by_channel", (q) =>
    q
      .eq("channel", channel)
      .gt("_creationTime", Date.now() - 2 * 60000)  // Messages from 2 minutes ago
      .lt("_creationTime", Date.now() - 60000)      // To 1 minute ago
  )
  .collect();

Ordering by Date

Convex automatically adds _creationTime as the final field to all indexes, which you can use for ordering. By default, Convex returns documents ordered by _creationTime in ascending order, but you can change this using the .order() method:

// Get messages, newest to oldest
const messages = await ctx.db.query("messages").order("desc").collect();

// Get messages, oldest to newest
const messages = await ctx.db.query("messages").order("asc").collect();

If you need to order by a custom date field, you should create an index that includes that field and then query using that index:

// Assuming you have an index "by_postedAt" on a "postedAt" field
const results = await ctx.db
  .query("posts")
  .withIndex("by_postedAt")
  .order("desc")  // newest first
  .collect();
#

When working with date ranges, be careful with using Date.now() in queries as it can cause issues with pagination. In some cases, using constants like Number.MAX_SAFE_INTEGER for upper bounds can be more reliable as discussed in the community.

Remember that when using indexes, you must follow the index field order in your queries, and inequality filters (like date ranges) can only be applied after all equality filters.

I hope this helps with your date-based queries in Convex!

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: