使Sort()在MongoDB查询中起作用

时间:2018-05-18 04:09:18

标签: mongodb sorting go

我在这里使用sort()对数据进行排序,但效果不佳。下面我发布了我的代码和输出: -

代码: -

  1. 结构声明

    import(
     "github.com/gin-gonic/gin"
     "gopkg.in/mgo.v2/bson"
     "strconv"
     "fmt"
     "time"
     "gopkg.in/mgo.v2"// for db
    )  
    type Schedule struct{
     Id           int                 `json:"_id" bson:"_id"`
     Day          string              `form:"day" json:"day" bson:"day"`
     StartDate    int64               `form:"start_date" json:"start_date" bson:"start_date"`
     EndDate      int64                `form:"end_date" json:"end_date" bson:"end_date"`
     StartTime    int64                `form:"start_time" json:"start_time" bson:"start_time"`
     EndTime      int64               `form:"end_time" json:"end_time" bson:"end_time"`
    }
    type Schedules []Schedule  
    
  2. 数据库功能

    func GetSchedulingListing(Query interface{}) (result Schedules, err error) {
     mongoSession := ConnectDb()
     sessionCopy := mongoSession.Copy()
     defer sessionCopy.Close()
     getCollection := mongoSession.DB("schedule2").C("schedule")
     err = getCollection.Find(Query).Select(bson.M{"start_date": 1, "end_date": 1}).Sort("start_date").All(&result)
     if err != nil {
       return result, err
     }
     return result, nil
    }
    
    func GetSchedule(c *gin.Context) {
     selected_day:= "Monday"
     conditions := bson.M{"day":selected_day}
     data, err := models.GetSchedulingListing(conditions) 
     for i := range data {
        start_date := data[i].StartDate
        end_date := data[i].EndDate
        days:= time.Unix(end_date,0).Sub(time.Unix(start_date,0)).Hours() / 24
        for i := 1; i <= int(days+1); i++ {
           if selected_day == time.Unix(start_date,0).Weekday().String() {
             fmt.Println(start_date)
           }
         start_date = start_date + 86400
        }
      }
    }
    
  3. 在上面的代码中,我在查询函数Sort("start_date")中使用GetSchedulingListing。但它不能很好地打印输出,如: -

    输出: -

     1525651200
     1526256000
     1526860800
     1527465600
     1525651200
     1526256000
     1526860800
     1527465600
    

    预期产出: -

     1525651200
     1525651200
     1526256000
     1526256000
     1526860800
     1526860800
     1527465600
     1527465600
    

    数据库记录: -

    {
     "_id" : 1,
     "day" : "Monday",
     "start_date" : NumberLong(1525132800),
     "end_date" : NumberLong(1527638400),
     "start_time" : NumberLong(22800),
     "end_time" : NumberLong(30000)
    }
    {
     "_id" : 2,
     "day" : "Monday",
     "start_date" : NumberLong(1525132800),
     "end_date" : NumberLong(1527638400),
     "start_time" : NumberLong(12000),
     "end_time" : NumberLong(19200)
    }
    

    查询检索的数据

    [{1  1525132800 1527638400 0 0} {2  1525132800 1527638400 0 0}]
     // because I'm using the `.Select(bson.M{"start_date": 1, "end_date": 1})` 
    

    任何人都可以告诉我为什么我没有得到预期输出的问题。谢谢。

0 个答案:

没有答案