mongodb/convert.go

43 lines
1.1 KiB
Go
Raw Permalink Normal View History

2022-12-14 08:49:46 +00:00
package mongodb
import (
"github.com/thoas/go-funk"
"go.mongodb.org/mongo-driver/bson/primitive"
"sort"
)
// ConvertObjectIDsToStrings ...
func ConvertObjectIDsToStrings(ids []primitive.ObjectID) []string {
return funk.Map(ids, func(item primitive.ObjectID) string {
return item.Hex()
}).([]string)
}
// UniqObjectIds ...
func UniqObjectIds(ids []primitive.ObjectID) []primitive.ObjectID {
idStr := ConvertObjectIDsToStrings(ids)
idStr = funk.UniqString(idStr)
return ConvertStringsToObjectIDs(idStr)
}
// ConvertStringsToObjectIDs ...
func ConvertStringsToObjectIDs(strValues []string) []primitive.ObjectID {
return funk.Map(strValues, func(item string) primitive.ObjectID {
2022-12-14 08:53:45 +00:00
return ConvertStringToObjectID(item)
2022-12-14 08:49:46 +00:00
}).([]primitive.ObjectID)
}
// ConvertStringToObjectID ...
func ConvertStringToObjectID(id string) primitive.ObjectID {
2022-12-14 08:55:03 +00:00
objID, _ := primitive.ObjectIDFromHex(id)
return objID
2022-12-14 08:49:46 +00:00
}
// SortObjectId ...
func SortObjectId(ids []primitive.ObjectID) []primitive.ObjectID {
sort.Slice(ids, func(i, j int) bool {
return ids[i].Timestamp().Before(ids[j].Timestamp())
})
return ids
}