Golang+MongoDB实现的增删改查demo - Go语言中文社区

Golang+MongoDB实现的增删改查demo


package main

import (
	"fmt"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type Person struct {
	NAME  string
	PHONE string
}
type Men struct {
	Persons []Person
}

const (
	URL = "localhost:27017" //连接mongoDB启动服务的端口号 你得先启动mongoDB服务
)

func main() {

	session, err := mgo.Dial(URL) //连接数据库
	if err != nil {
		panic(err)
	}
	defer session.Close()
	//Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)

	db := session.DB("test") //数据库名称

	collection := db.C("person") //如果该集合已经存在的话,则直接返回

	//*****集合中元素数目********
	countNum, err := collection.Count()
	if err != nil {
		panic(err)
	}
	fmt.Println("Things objects count: ", countNum)

	//*******插入元素*******
	temp := &Person{
		PHONE: "7017986",
		NAME:  "Ale",
	}
	//一次可以插入多个对象 插入两个Person对象
	err = collection.Insert(&Person{"Ale", "13798245114"}, temp)
	if err != nil {
		panic(err)
	}

	//*****查询单条数据*******
	result := Person{}

	err = collection.Find(bson.M{"phone": "13798245114"}).One(&result) //查询单条phone为13798245114的结果
	fmt.Println("Phone:", result.NAME, result.PHONE)                   //输出单条phone为13798245114的结果

	//*****查询多条数据*******
	var personAll Men //存放结果
	iter := collection.Find(nil).Iter()
	for iter.Next(&result) {
		fmt.Printf("Result: %vn", result)
		personAll.Persons = append(personAll.Persons, result)
	}

	//*******更新数据**********
	//修改所有name为ddd的对象成name为ddd
	_, err = collection.UpdateAll(bson.M{"name": "Ale"}, bson.M{"$set": bson.M{"name": "ddd"}})

	//修改name为ddd的对象成phone为666666
	err = collection.Update(bson.M{"name": "ddd"}, bson.M{"$set": bson.M{"phone": "666666"}})

	//修改所有name为ddd的对象成name为xiaomin,phone为123456
	_, err = collection.UpdateAll(bson.M{"name": "ddd"}, bson.M{"$set": bson.M{"name": "xiaomin", "phone": "123456"}})

	//******删除所有name为xiaomin的数据************
	_, err = collection.RemoveAll(bson.M{"name": "xiaomin"})
}

运行截图



参考博客  mgo使用指南

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_32340877/article/details/78854016
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-04-18 22:51:20
  • 阅读 ( 1656 )
  • 分类:数据库

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢