内容简介:插入数据库通常情况下针对每个表创建一个结构体,但是mongodb是schemaless,文档数据库,对字段没有严格要求
21天精品区块链课程免费学习,深入实战行家带路,助力开发者轻松玩转区块链! >>>
golang mongodb插入insert数据demo
插入数据库通常情况下针对每个表创建一个结构体,但是 mongodb 是schemaless,文档数据库,对字段没有严格要求
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"io/ioutil"
"net/http"
"encoding/json"
//"time"
)
type Count struct {
I int
}
var session *mgo.Session
var err error
func main() {
session, err = mgo.Dial("127.0.0.1:27017")
if err != nil {
fmt.Print(err)
}
defer session.Close()
http.HandleFunc("/insert",insert)
http.ListenAndServe(":9999",nil)
////b := session.DB("testdb").C("test1").Bulk() // 第二种
//c := session.DB("testdb").C("test1") //第一种
//start := time.Now()
//for i := 0; i < 100000; i++ {
// //b.Insert(&Count{i}) //第二种
// c.Insert(&Count{i}) //第一种
//}
////b.Run() // 第二种
//duration := time.Since(start)
//fmt.Printf("insert 10w: %v", duration.Seconds()*1e6/float64(1000))
}
func insert(w http.ResponseWriter,r *http.Request){
s, _ := ioutil.ReadAll(r.Body)
var p []interface{}
err := json.Unmarshal([]byte(s), &p)
if err!=nil{
fmt.Fprint(w,"json格式错误")
fmt.Println(err)
return
}
c := session.DB("testdb").C("test1") //第一种
//start := time.Now()
for _,mp :=range p{
//mp["time"]=start
err=c.Insert(∓) //第一种
if err != nil {
fmt.Println(mp)
panic(err)
}
fmt.Println(err)
}
fmt.Println( p )
}
func test() {
//Create the Json string
var data = `
{
"id": 12423434,
"Name": "Fernando"
}
`
//Marshal the json to a map
var result map[string]interface{}
err := json.Unmarshal([]byte(data), &result)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println(result)
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Introduction to Linear Optimization
Dimitris Bertsimas、John N. Tsitsiklis / Athena Scientific / 1997-02-01 / USD 89.00
"The true merit of this book, however, lies in its pedagogical qualities which are so impressive..." "Throughout the book, the authors make serious efforts to give geometric and intuitive explanations......一起来看看 《Introduction to Linear Optimization》 这本书的介绍吧!