How to install and use MongoDB in golang

PHPz
Release: 2023-04-04 17:18:01
Original
924 people have browsed it

在进行golang开发时,使用MongoDB作为数据库是非常常见的。下面就让我们来一步步学习如何在golang中安装使用MongoDB。

  1. 安装MongoDB

首先需要在官网上下载MongoDB的安装包,地址为https://www.mongodb.com/download-center/community。

下载完成后,运行安装程序。

  1. 配置MongoDB

安装完成后需要进行一些配置。首先需要配置MongoDB的数据存放路径。可以在默认安装路径中选择一个文件夹,或者创建一个新的文件夹。

在创建文件夹时需要注意一下权限问题,确保当前用户有读写权限。

另外,与安装相关的配置需要修改默认的配置文件mongod.conf。可以在MongoDB的安装文件夹MongoDB\Server\X.X\bin中找到该文件,把注释去掉并在末尾添加以下几行:

#bind_ip = 127.0.0.1
bind_ip_all = true
Copy after login

这些配置将MongoDB配置文件中的IP绑定取消,并启用所有IP的绑定,这是为了避免在开发时设置IP绑定而导致的复杂性问题。

  1. 启动MongoDB

在安装完MongoDB并进行过配置后,就可以启动MongoDB服务了。可以直接在命令行中输入以下指令:

mongod --config "D:\MongoDB\Server\4.0\bin\mongod.cfg" --dbpath "D:\MongoDB\data\db"
Copy after login

其中--config参数指定了MongoDB的配置文件的路径,--dbpath参数指定了数据存储的路径。此外还可以添加--nojournal参数来禁用日志功能,这也可以在开发中起到一些优化作用。

4.使用MongoDB

MongoDB安装并启动后,就可以开始使用了。下面给出一个MongoDB的基本操作示例:

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type Person struct {
    Name  string
    Phone string
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    if err != nil {
        log.Fatal(err)
    }

    collection := client.Database("test").Collection("people")
    _, err = collection.InsertOne(ctx, &Person{"John", "123"})
    if err != nil {
        log.Fatal(err)
    }

    filter := Person{Phone: "123"}
    update := Person{Name: "NewJohn"}

    result, err := collection.ReplaceOne(
        ctx,
        filter,
        update,
    )
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Matched %v documents and updated %v documents.\n", result.MatchedCount, result.ModifiedCount)
}
Copy after login

这是一个简单的golang程序,它使用了mongo-driver库来访问MongoDB数据库。在这个程序中,我们首先创建了一个Person类型,它拥有一个名字和一个电话号码字段。然后,我们连接到了MongoDB的test数据库,并获取了people集合。接下来,我们向集合中插入了John的记录,并使用电话号码查询到了John的记录并将其名字替换为NewJohn。

以上就是golang中MongoDB的安装和使用过程。是不是很简单呢?

The above is the detailed content of How to install and use MongoDB in golang. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!