Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何构建mgo查询?_Go_Mgo_Revel - Fatal编程技术网

如何构建mgo查询?

如何构建mgo查询?,go,mgo,revel,Go,Mgo,Revel,我正在用revel和mgo做一个小项目(实践),但在构建查询时,我发现搜索功能出了问题。代码如下所示: conditions := make(bson.M, 0) conditions["status"] = bson.M{"$ne": "delete"} if item, ok := paramsPost["title"]; ok { if item[0] != "" { conditions["title"] = bson.RegEx{Pattern: item[0

我正在用revel和mgo做一个小项目(实践),但在构建查询时,我发现搜索功能出了问题。代码如下所示:

conditions := make(bson.M, 0)
conditions["status"] = bson.M{"$ne": "delete"}

if item, ok := paramsPost["title"]; ok {
    if item[0] != "" {
        conditions["title"] = bson.RegEx{Pattern: item[0]}
    }
}
if item, ok := paramsPost["from_date"]; ok {
    if item[0] != "" {
        conditions["publishdate"] = bson.M{}
        fromDate, _ := time.Parse("2006-01-02", item[0])
        conditions["publishdate"]["$gte"] = fromDate.Unix()
    }
}

if item, ok := paramsPost["to_date"]; ok {
    if _, ok := conditions["publishdate"]; !ok {
        conditions["publishdate"] = bson.M{}
    }
    if item[0] != "" {
        toDate, _ := time.Parse("2006-01-02", item[0])
        conditions["publishdate"]["$lte"] = toDate.Unix()
    }
}
我得到了一些错误信息:

invalid operation: conditions["publishdate"]["$gte"] (index of type interface {})

我知道我做错了什么,但我不知道为什么,以及如何解决。有人能帮我吗?谢谢

bson.M
是一个
map[string]接口{}
()

那么在

conditions["publishdate"]["$gte"] = fromDate.Unix()
在映射中查找
publishdate
时,需要从
interface{}
bson.M
执行类型断言

相反,您可以将代码重构为

publishdate:= bson.M{}
// ... your logic goes here
conditions["publishdate"] = publishDate

保存不必要的映射查找和类型断言。

bson.M
是一个
map[string]接口{}
()

那么在

conditions["publishdate"]["$gte"] = fromDate.Unix()
在映射中查找
publishdate
时,需要从
interface{}
bson.M
执行类型断言

相反,您可以将代码重构为

publishdate:= bson.M{}
// ... your logic goes here
conditions["publishdate"] = publishDate

为了节省不必要的地图查找和类型断言。

非常感谢~Alex,我现在就开始工作了。看起来我用PHP的方式处理golang结构~haha。你真的帮了我很多。非常感谢~Alex,我现在就开始工作了。看起来我用PHP的方式处理golang结构~haha。你真的帮了我很多忙。