你可以使用mgo和Go来查询MongoDB的日期范围。

huangapple go评论71阅读模式
英文:

How can I query MongoDB with date range using mgo and Go?

问题

你好,我有一个名为"my_sales"的集合,其中包含字段product_name、price和sale_date。

我的文档如下所示:

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

你在Mongo Shell中尝试了以下查询:

db.my_sales.find({ sale_date: { $gt: ISODate("2014-11-04"), $lt: new ISODate("2014-11-05") }});

它给出了正确的结果。现在我需要使用Golang进行相同的查询,我尝试了以下代码:

var sales_his []Sale
err := c.Find(bson.M{"sale_date": bson.M{ "$gt": "ISODate("+date_from+")", "$lt": "ISODate("+date_to+")" } }).All(&sales_his)

但它返回了空结果,请帮忙看看。

英文:

Hi I have a collection named "my_sales" having fields product_name, price, sale_date.

My doc looks like

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

I tried in mongo shell like this

 db.my_sales.find({ sale_date: { $gt: ISODate("2014-11-04"), $lt: new ISODate("2014-11-05") });

It giving the correct result. Now I need to query same thing using golang
I tried like this

 var sales_his []Sale
 err := c.Find(bson.M{"sale_date":bson.M{ "$gt": "ISODate("+date_from+")", "$lt": "ISODate("+date_to+")" }    }).All(&sales_his)

Its giving null result please help

答案1

得分: 49

mgo支持使用BSON日期的time.Time

所以,如果你的结构体如下所示:

type Sale struct {
	ProductName string    `bson:"product_name"`
	Price       int       `bson:"price"`
	SaleDate    time.Time `bson:"sale_date"`
}

那么你可以像这样查询它:

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)
英文:

mgo supports time.Time for BSON dates.

So if your struct looks like this:

type Sale struct {
	ProductName string    `bson:"product_name"`
	Price       int       `bson:"price"`
	SaleDate    time.Time `bson:"sale_date"`
}

Then you can query it like this:

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)

答案2

得分: 4

我有一种新的查询日期范围的方法:

// 转换为日期
fromTime := time.Unix(1509358405981/1000, 0)     

// 将日期转换为带有时间的ObjectID    
fromObjectBson := bson.NewObjectIdWithTime(fromTime)

// 查询条件     
bson.M{"_id": bson.M{"$gt": fromObjectBson}} 

这将加快你的查询速度。

英文:

I have new way to query date range:

// convert to date
fromTime := time.Unix(1509358405981/1000, 0)     

// Convert date to ObjectID with time    
fromObjectBson := bson.NewObjectIdWithTime(fromTime)

// condition     
bson.M{"_id":bson.M{"$gt": fromObjectBson}} 

This will speedup your query.

答案3

得分: -1

你也可以查看这个。如果你使用这种方法,那么请使用解析:

db.getCollection('user').find({
    createdOn: {
        $gt: ISODate("2020-01-01T00:00:00.000Z"),
        $lt: ISODate("2020-03-01T00:00:00.000Z")
    }
})

不使用解析的函数:使用字符串获取值

db, err := GetDB()
if err != nil {
    return nil, err
}
defer db.Session.Close()

var date []models.User

coll := db.C(constants.USERTABLE)

findQuery := bson.M{"createdOn": bson.M{"$gt": echo.FromDate, "$lt": echo.ToDate}}

shared.BsonToJSONPrint(findQuery)

err = coll.Find(findQuery).All(&date)
if err != nil {
    return nil, err
}
return date, nil

}

英文:

You Can also check this out. If you are using this method then use parse:

db.getCollection('user').find({
    createdOn: {
        $gt: ISODate("2020-01-01T00:00:00.000Z"),
        $lt: ISODate("2020-03-01T00:00:00.000Z")
    }
})

Function without parsing: Get values using string

db, err := GetDB()
if err != nil {
	return nil, err
}
defer db.Session.Close()

var date []models.User

coll := db.C(constants.USERTABLE)

findQuery := bson.M{"createdOn": bson.M{"$gt": echo.FromDate, "$lt": echo.ToDate}}

shared.BsonToJSONPrint(findQuery)

err = coll.Find(findQuery).All(&date)
if err != nil {
	return nil, err
}
return date, nil
}

huangapple
  • 本文由 发表于 2014年11月6日 15:31:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/26773979.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定