Home  >  Article  >  Backend Development  >  How to Query MongoDB Date Ranges Using Go and Mgo?

How to Query MongoDB Date Ranges Using Go and Mgo?

DDD
DDDOriginal
2024-11-08 14:06:02564browse

How to Query MongoDB Date Ranges Using Go and Mgo?

Querying MongoDB Date Ranges Using Go and Mgo

When working with MongoDB collections that store dates, it's essential to understand how to query data within specified date ranges. This article addresses a query issue encountered when using Golang and Mgo.

The sample MongoDB collection named "my_sales" has documents with fields including "product_name," "price," and "sale_date," represented as ISODates. The objective is to retrieve sales records that fall within a specific date range.

In the MongoDB shell, the query looks like this:

However, when attempting to perform the same query in Golang using the Mgo driver, the following code returns no results:

The issue lies in the way Mgo handles BSON dates. For Go structs, time.Time should be used for date fields. Thus, the Sale struct should be defined as follows:

With this updated struct, the correct query in Golang is:

The above is the detailed content of How to Query MongoDB Date Ranges Using Go and Mgo?. 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