dqt83336 2014-11-06 07:31
浏览 157
已采纳

如何使用mgo和Go查询日期范围的MongoDB?

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

  • 写回答

2条回答 默认 最新

  • donglu3087 2014-11-06 08:30
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 adb连接不到手机是怎么回事?
  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目