Insert Interface data with integer and double fields via Golang to MongoDB but integer fields was stored as double

huangapple go评论85阅读模式
英文:

Insert Interface data with integer and double fields via Golang to MongoDB but integer fields was stored as double

问题

使用Golang将带有整数和双精度字段的接口数据插入MongoDB时,整数字段被存储为双精度的问题。

我需要从队列中消费非结构化数据(JSON格式),并将数据批量插入MongoDB,但整数字段被存储为双精度。

示例代码:

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	mongoURI := fmt.Sprintf("mongodb://%s:%s@%s:%d", "root", "root", "localhost", 27017)
	ctxtimeout, cancelCtx := context.WithTimeout(context.Background(), 60*time.Second)
	mongoConnection, err := mongo.NewClient(options.Client().ApplyURI(mongoURI))
	if err != nil {
		log.Fatal(err.Error())
	}
	defer cancelCtx()
	err = mongoConnection.Connect(ctxtimeout)
	if err != nil {
		log.Fatal(err.Error())
	}
	defer mongoConnection.Disconnect(ctxtimeout)
	mongoDatabase := mongoConnection.Database("dbname")
	mongoCollection := mongoDatabase.Collection("posts")

	str := `{ "number1": 10, "number2": 20.1 }`
	var data map[string]interface{}
	json.Unmarshal([]byte(str), &data)
	reMar, _ := json.Marshal(data)
	fmt.Println(string(reMar))
	mongoCollection.InsertOne(ctxtimeout, data)
}

变量str存储了从队列中获取的示例数据。

这是存储到MongoDB的输出。number1字段应该存储为整数,但它被存储为双精度。

那么,如何将其存储为整数而不是双精度?

英文:

Insert Interface data with integer and double fields via Golang to MongoDB but integer fields was stored as double

I have to consume unstructure data from queue (JSON format) and bulk the data to MongoDB but the integer fields was store as double

Example Code

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	mongoURI := fmt.Sprintf("mongodb://%s:%s@%s:%d", "root", "root", "localhost", 27017)
	ctxtimeout, cancelCtx := context.WithTimeout(context.Background(), 60*time.Second)
	mongoConnection, err := mongo.NewClient(options.Client().ApplyURI(mongoURI))
	if err != nil {
		log.Fatal(err.Error())
	}
	defer cancelCtx()
	err = mongoConnection.Connect(ctxtimeout)
	if err != nil {
		log.Fatal(err.Error())
	}
	defer mongoConnection.Disconnect(ctxtimeout)
	mongoDatabase := mongoConnection.Database("dbname")
	mongoCollection := mongoDatabase.Collection("posts")

	str := `{ "number1": 10, "number2": 20.1 }`
	var data map[string]interface{}
	json.Unmarshal([]byte(str), &data)
	reMar, _ := json.Marshal(data)
	fmt.Println(string(reMar))
	mongoCollection.InsertOne(ctxtimeout, data)
}

The str variable is store the example data that I got from queue

This is the output that store to MongoDB. The number1 fields should stored as Int but it stored as Double

So, How to stored it as Int not double ?

Insert Interface data with integer and double fields via Golang to MongoDB but integer fields was stored as double

答案1

得分: 1

我刚刚发现可以使用json.NewDecoderUseNumber()来解决问题。

示例代码

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"strings"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	mongoURI := fmt.Sprintf("mongodb://%s:%s@%s:%d", "root", "root", "localhost", 27017)
	ctxtimeout, cancelCtx := context.WithTimeout(context.Background(), 60*time.Second)
	mongoConnection, err := mongo.NewClient(options.Client().ApplyURI(mongoURI))
	if err != nil {
		log.Fatal(err.Error())
	}
	defer cancelCtx()
	err = mongoConnection.Connect(ctxtimeout)
	if err != nil {
		log.Fatal(err.Error())
	}
	defer mongoConnection.Disconnect(ctxtimeout)
	mongoDatabase := mongoConnection.Database("influencerdirectory")
	mongoCollection := mongoDatabase.Collection("posts")

	str := `{ "number1": 10, "number2": 20.1 }`
	var data map[string]interface{}
	d := json.NewDecoder(strings.NewReader(str))
	d.UseNumber()
	d.Decode(&data)
	// json.Unmarshal([]byte(str), &data)
	reMar, _ := json.Marshal(data)
	fmt.Println(string(reMar))
	mongoCollection.InsertOne(ctxtimeout, data)
}

结果:

Insert Interface data with integer and double fields via Golang to MongoDB but integer fields was stored as double

参考:https://stackoverflow.com/questions/53422587/need-to-parse-integers-in-json-as-integers-not-floats

英文:

I just found solution by using json.NewDecoder with UseNumber()

Example code

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"strings"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
	mongoURI := fmt.Sprintf("mongodb://%s:%s@%s:%d", "root", "root", "localhost", 27017)
	ctxtimeout, cancelCtx := context.WithTimeout(context.Background(), 60*time.Second)
	mongoConnection, err := mongo.NewClient(options.Client().ApplyURI(mongoURI))
	if err != nil {
		log.Fatal(err.Error())
	}
	defer cancelCtx()
	err = mongoConnection.Connect(ctxtimeout)
	if err != nil {
		log.Fatal(err.Error())
	}
	defer mongoConnection.Disconnect(ctxtimeout)
	mongoDatabase := mongoConnection.Database("influencerdirectory")
	mongoCollection := mongoDatabase.Collection("posts")

	str := `{ "number1": 10, "number2": 20.1 }`
	var data map[string]interface{}
	d := json.NewDecoder(strings.NewReader(str))
	d.UseNumber()
	d.Decode(&data)
	// json.Unmarshal([]byte(str), &data)
	reMar, _ := json.Marshal(data)
	fmt.Println(string(reMar))
	mongoCollection.InsertOne(ctxtimeout, data)
}

Result:

Insert Interface data with integer and double fields via Golang to MongoDB but integer fields was stored as double

Ref : https://stackoverflow.com/questions/53422587/need-to-parse-integers-in-json-as-integers-not-floats

huangapple
  • 本文由 发表于 2021年10月15日 18:07:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/69583107.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定