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: %v\n", 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使用指南

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

《源码好优多》

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值