亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

通過始終保留相同的順序將映射編入 BSON

通過始終保留相同的順序將映射編入 BSON

Go
ABOUTYOU 2022-08-30 22:03:15
我有一個地圖,它是我從一段字符串創建的。然后我想將其封送為bson格式,作為索引插入mongodb。但是,由于地圖在Golang中的創建方式,我每次都會得到不同的索引順序(有時是它的abc,有時是它的bac,cba...)。如何確保創建的封送索引始終按相同的順序排列?fields := ["a", "b", "c"] compoundIndex := make(map[string]int)for _, field := range fields {    compoundIndex[field] = 1}data, err := bson.Marshal(compoundIndex)fmt.Println(string(data)) // This output is always in a different order than the desired abc
查看完整描述

1 回答

?
慕標琳琳

TA貢獻1830條經驗 獲得超9個贊

使用文檔 bson 的有序表示形式。D:


var compoundIndex bson.D

for _, field := range fields {

    compoundIndex = append(compoundIndex, bson.E{Key: field, Value: 1})

}

data, err := bson.Marshal(compoundIndex)

fmt.Println(string(data)) // The elements are always printed in the same order.

在 Playground 上運行一個示例。


查看完整回答
反對 回復 2022-08-30
  • 1 回答
  • 0 關注
  • 99 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號