Home  >  Article  >  Backend Development  >  How do you Query MongoDB with Date Range using mgo and Go?

How do you Query MongoDB with Date Range using mgo and Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-05 16:35:02483browse

How do you Query MongoDB with Date Range using mgo and Go?

Querying MongoDB with Date Range Using mgo and Go

MongoDB's powerful query capabilities allow for precise filtering of data based on specific criteria, including date ranges. Using mgo, a popular Go library for MongoDB, querying within date ranges is straightforward.

Consider the following MongoDB document:

{
    "_id" : ObjectId("5458b6ee09d76eb7326df3a4"),
    "product_name" : "product1",
    "price" : 200,
    "sale_date" : ISODate("2014-11-04T11:22:19.589Z")
}

To query this document for documents sold within a specific date range, the following steps can be taken:

  1. Create a Go Struct for Sales Data:

    <code class="go">type Sale struct {
        ProductName string    `bson:"product_name"`
        Price       int       `bson:"price"`
        SaleDate    time.Time `bson:"sale_date"`
    }</code>
  2. Parse Date Ranges from Strings:

    <code class="go">fromDate, err := time.Parse(timeLayout, dateFrom)
    if err != nil {
        return err
    }
    toDate, err := time.Parse(timeLayout, dateTo)
    if err != nil {
        return err
    }</code>
  3. Query with Date Range:

    <code class="go">var sales []Sale
    err = c.Find(
        bson.M{
            "sale_date": bson.M{
                "$gt": fromDate,
                "$lt": toDate,
            },
        },
    ).All(&amp;sales)</code>

By utilizing the $gt and $lt MongoDB operators, the query selects documents where the sale_date field exceeds fromDate and falls short of toDate, effectively filtering sales within the specified date range.

The above is the detailed content of How do you Query MongoDB with Date Range using mgo and Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn