Home Database Mysql Tutorial golang使用mgo连接MongoDB

golang使用mgo连接MongoDB

Jun 07, 2016 pm 03:29 PM
golang mongodb use connect

github:https://github.com/ZhangzheBJUT/blog/blob/master/mgo.md 现在MongoDB官方还没有推出关于官方支持的golang的driver,推荐使用的是mgo. mgo的详细文档说明:http://godoc.org/labix.org/v2/mgo 下面是我开发中自己写的一个用mgo连接MongoDB数据库的使

github:https://github.com/ZhangzheBJUT/blog/blob/master/mgo.md

现在MongoDB官方还没有推出关于官方支持的golang的driver,推荐使用的是mgo. mgo的详细文档说明:http://godoc.org/labix.org/v2/mgo
下面是我开发中自己写的一个用mgo连接MongoDB数据库的使用实例。
package main

import (

    "fmt"
    "labix.org/v2/mgo"
    "labix.org/v2/mgo/bson"
)

type Person struct {
    NAME  string
    PHONE string
}
type Men struct {
    Persons []Person
}
const = (
    URL = "192.168.2.175:27017"
)
func main() {

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

    db := session.DB("mydb")     //数据库名称
    collection := db.C("person") //如果该集合已经存在的话,则直接返回


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

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

    //*****查询单条数据*******
    result := Person{}
    err = collection.Find(bson.M{"phone": "456"}).One(&result)
    fmt.Println("Phone:", result.NAME, result.PHONE)

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

    //*******更新数据**********
    err = collection.Update(bson.M{"name": "ccc"}, bson.M{"$set": bson.M{"name": "ddd"}})
    err = collection.Update(bson.M{"name": "ddd"}, bson.M{"$set": bson.M{"phone": "12345678"}})
    err = collection.Update(bson.M{"name": "aaa"}, bson.M{"phone": "1245", "name": "bbb"})

    //******删除数据************
    _, err = collection.RemoveAll(bson.M{"name": "Ale”})
Copy after login
} 
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

How to ensure concurrency is safe and efficient when writing multi-process logs? How to ensure concurrency is safe and efficient when writing multi-process logs? Apr 02, 2025 pm 03:51 PM

Efficiently handle concurrency security issues in multi-process log writing. Multiple processes write the same log file at the same time. How to ensure concurrency is safe and efficient? This is a...

How to solve the problem of Golang generic function type constraints being automatically deleted in VSCode? How to solve the problem of Golang generic function type constraints being automatically deleted in VSCode? Apr 02, 2025 pm 02:15 PM

Automatic deletion of Golang generic function type constraints in VSCode Users may encounter a strange problem when writing Golang code using VSCode. when...

How to use Golang to implement Caddy-like background running, stop and reload functions? How to use Golang to implement Caddy-like background running, stop and reload functions? Apr 02, 2025 pm 02:12 PM

How to implement background running, stopping and reloading functions in Golang? During the programming process, we often need to implement background operation and stop...

What is the rotation strategy for Golang logs on Debian What is the rotation strategy for Golang logs on Debian Apr 02, 2025 am 08:39 AM

In Debian systems, Go's log rotation usually relies on third-party libraries, rather than the features that come with Go standard libraries. lumberjack is a commonly used option. It can be used with various log frameworks (such as zap and logrus) to realize automatic rotation and compression of log files. Here is a sample configuration using the lumberjack and zap libraries: packagemainimport("gopkg.in/natefinch/lumberjack.v2""go.uber.org/zap""go.uber.org/zap/zapcor

How to implement operations on Linux iptables linked lists in Golang? How to implement operations on Linux iptables linked lists in Golang? Apr 02, 2025 am 10:18 AM

Using Golang to implement Linux...

From the front-end to the back-end, is it more conducive to career development to choose to learn Java or Golang? From the front-end to the back-end, is it more conducive to career development to choose to learn Java or Golang? Apr 02, 2025 pm 02:21 PM

Exploring the learning path from front-end to back-end As a front-end development engineer, you have a preliminary understanding of Node.js, and have participated in small projects to master...

See all articles