我是 mongoDB 的新手,目前我們正在嘗試將我們的舊 mgo 驅(qū)動程序遷移到 go mongo-driver在我們的舊代碼中,我們使用來自全局標(biāo)志 mgo 驅(qū)動程序的如下內(nèi)容//where apps is a structapps := []model.App{}err = mgo.Collection.Find(query).Skip(skipCount).Limit(MaxResults).Sort("-starttime").All(&apps)因此,對于新的 mongo-driver,我使用 Find 嘗試了類似下面的方法,但是沒有用。 // Set FindOneOptions findOpt := options.Find() findOpt.SetSkip(int64(skipCount)) limitVal := appsbody.MaxResults findOpt.SetLimit(int64(limitVal)) findOpt.SetSort("-starttime") err = mgo.Collection.Find(query, findOpt).All(context.TODO(), &apps)在上面的代碼片段中,params 查詢的類型是 map[string]interface{}。當(dāng)我嘗試記錄查詢時,Key = type Value = dbuser兩者都是字符串類型查詢值最初是通過使用傳遞的query := url.Values{},這種情況下查詢類型將是map[string][]string我想后來它被通過了,因為map[string]interface{}不確定這是否會導(dǎo)致這個問題并且無法與正確的查詢格式混合params,所以我什至嘗試使用下面的代碼轉(zhuǎn)換它,但仍然沒有幫助我解決問題。 //do a type conversion for the original query q := make(map[string]interface{}, len(query)) for key, value := range query { q[key] = value }當(dāng)我嘗試運行代碼時,它無法執(zhí)行 Find 操作并且我得到以下錯誤并拋出 nil 指針cannot transform type string to a BSON Document: WriteString can only write while positioned on a Element or Value but is positioned on a TopLevelpanic: runtime error: invalid memory address or nil pointer dereference panic: runtime error: invalid memory address or nil pointer dereference panic: runtime error: invalid memory address or nil pointer dereference[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x564171020634]goroutine 1 [running]:go.mongodb.org/mongo-driver/mongo.(*Cursor).closeImplicitSession(0x5641708ab4e0?) go.mongodb.org/mongo-driver@v1.10.3/mongo/cursor.go:309 +0x14panic({0x5641716c9440, 0x56417200c2d0}) runtime/panic.go:884 +0x212go.mongodb.org/mongo-driver/mongo.(*Cursor).Close(0xa1?, {0x5641718f9c30?, 0xc00003a078?}) go.mongodb.org/mongo-driver@v1.10.3/mongo/cursor.go:222 +0x5fpanic({0x5641716c9440, 0x56417200c2d0}) runtime/panic.go:884 +0x212不確定我在這里犯了什么錯誤,誰能幫我解決這個問題?
1 回答

慕工程0101907
TA貢獻1887條經(jīng)驗 獲得超5個贊
問題在于排序值。它必須是一個文檔,而不是一個簡單的string. 它可以是一個映射,一個bson.M(它也是一個映射)或一個bson.D值(或任何其他“很好地”編組到 BSON 中的值,例如結(jié)構(gòu))。
如果您只使用單個字段進行排序,最簡單的是一個bson.M. 另請注意,可以鏈接對選項的方法調(diào)用(它們返回接收者):
findOpt := options.Find().
SetSkip(int64(skipCount)).
SetLimit(int64(appsbody.MaxResults)).
SetSort(bson.M{"starttime": -1})
如果您有多個排序鍵,順序很重要,在這種情況下使用bson.D文檔(地圖是無序的,bson.D是鍵值對的有序列表):
findOpt := options.Find().
SetSkip(int64(skipCount)).
SetLimit(int64(appsbody.MaxResults)).
SetSort(bson.D{{Key:"starttime", Value: -1}, {Key:"other", Value: 1}})
- 1 回答
- 0 關(guān)注
- 100 瀏覽
添加回答
舉報
0/150
提交
取消