Go实战--golang中MongoDB(mgo) 插入interface 顶

栏目: Go · 发布时间: 7年前

内容简介:插入数据库通常情况下针对每个表创建一个结构体,但是mongodb是schemaless,文档数据库,对字段没有严格要求

21天精品区块链课程免费学习,深入实战行家带路,助力开发者轻松玩转区块链! >>> Go实战--golang中MongoDB(mgo) 插入interface 顶

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)
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

How to Build a Billion Dollar App

How to Build a Billion Dollar App

George Berkowski / Little, Brown Book Group / 2015-4-1 / USD 24.95

Apps have changed the way we communicate, shop, play, interact and travel and their phenomenal popularity has presented possibly the biggest business opportunity in history. In How to Build a Billi......一起来看看 《How to Build a Billion Dollar App》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

html转js在线工具
html转js在线工具

html转js在线工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具