Here I'm Sorting my data using the sort()
but it not works well. Below I posted my code and output too:-
Code:-
-
Struct declared
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
-
Database functions
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 } } }
In the above code I'm using Sort("start_date")
in query function GetSchedulingListing
. But it not works well it prints the output like:-
Output:-
1525651200
1526256000
1526860800
1527465600
1525651200
1526256000
1526860800
1527465600
Expected output:-
1525651200
1525651200
1526256000
1526256000
1526860800
1526860800
1527465600
1527465600
Database record:-
{
"_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)
}
Data retrieved by the Query
[{1 1525132800 1527638400 0 0} {2 1525132800 1527638400 0 0}]
// because I'm using the `.Select(bson.M{"start_date": 1, "end_date": 1})`
Can anyone tell whats the problem there why I'm not getting my Expected Output. Thank you.