我是 mongoDB 的新手,目前我們正在嘗試將舊的 mgo 驅動程式遷移到mongo-driver
在我們的舊代碼中,我們使用如下全域符號 mgo 驅動程式中的內容
//where apps is a struct
apps := []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)
在上面的代碼片段中,引數查詢的型別是 map[string]interface{}.
當我嘗試記錄查詢時,Key = type Value = dbuser兩者都是字串型別查詢值最初是通過 using 傳遞的query := url.Values{},這種情況下查詢型別將是map[string][]string
我認為稍后通過map[string]interface{}不確定這是否會導致此問題并且無法與正確的查詢格式混合params,所以我什至嘗試使用下面的代碼進行轉換,但仍然沒有幫助我解決問題。
//do a type conversion for the original query
q := make(map[string]interface{}, len(query))
for key, value := range query {
q[key] = value
}
當我嘗試運行代碼時,它無法執行查找操作并且我得到以下錯誤并拋出 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 TopLevel
panic: 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/[email protected]/mongo/cursor.go:309 0x14
panic({0x5641716c9440, 0x56417200c2d0})
runtime/panic.go:884 0x212
go.mongodb.org/mongo-driver/mongo.(*Cursor).Close(0xa1?, {0x5641718f9c30?, 0xc00003a078?})
go.mongodb.org/mongo-driver@v1.10.3/mongo/cursor.go:222 0x5f
panic({0x5641716c9440, 0x56417200c2d0})
runtime/panic.go:884 0x212
go.mongodb.org/mongo-driver/mongo.(*Cursor).All(0x0, {0x5641718f9c30, 0xc00003a078}, {0x5641715fa1c0?, 0xc0001d6480?})
go.mongodb.org/mongo-driver@v1.10.3/mongo/cursor.go:251 0x1ff
cr/dev/usvcs/apps/appDBAccess.DbService.GetApps({{0x5641718fda98, 0xc000484960}, {0x5641718f7228, 0xc000012750}, {0x5641718fce68, 0xc000014030}, {0x564171901cb8, 0x5641720bc5d8}}, 0xc0001dbbf0, {0x0, ...})
不知道我在這里犯了什么錯誤,有人可以幫我嗎?
uj5u.com熱心網友回復:
問題在于排序值。它必須是一個檔案,而不是一個簡單的string. 它可能是一個映射、一個bson.M(它也是一個映射)或一個bson.D值(或任何其他“很好地”編組到 BSON 中的值,例如結構)。
如果您只使用單個欄位進行排序,最簡單的是bson.M. 另請注意,選項上的方法呼叫可以鏈接起來(它們回傳接收者):
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}})
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/524282.html
標籤:mongodb去mongodb查询mongo-gogolang-迁移
上一篇:沒有埠轉發的調度器-作業者集群
