Home >Backend Development >Golang >How to Query MongoDB Date Ranges with Mgo and Go?

How to Query MongoDB Date Ranges with Mgo and Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-08 04:35:01635browse

How to Query MongoDB Date Ranges with Mgo and Go?

Querying MongoDB Date Range with Mgo and Go

In MongoDB, documents can be queried based on date ranges. To achieve this in Go using mgo, the following steps can be taken:

Define a Struct for the Document

For example, suppose a collection named "my_sales" has the following fields: "product_name," "price," and "sale_date." A corresponding Go struct can be defined as:

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

Query with mgo

Once the struct is defined, you can proceed with the query using mgo. Consider the following example:

<code class="go">fromDate := time.Date(2014, time.November, 4, 0, 0, 0, 0, time.UTC)
toDate := time.Date(2014, time.November, 5, 0, 0, 0, 0, time.UTC)

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

Here, the $gt (greater than) and $lt (less than) operators are used to specify the desired date range for the "sale_date" field. The result is stored in the sales_his slice.

The above is the detailed content of How to Query MongoDB Date Ranges with 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