Home  >  Article  >  Backend Development  >  How to use mgo to query MongoDB in golang

How to use mgo to query MongoDB in golang

PHPz
PHPzOriginal
2023-04-25 18:28:12604browse

In Golang, querying MongoDB is a very important task. mgo is a very popular MongoDB driver that provides a rich API for CRUD operations. This article will introduce how to use mgo to query MongoDB.

Install mgo

To use mgo, you first need to install it. It can be installed using the go get command. Open a terminal and run the following command:

go get gopkg.in/mgo.v2

This will download mgo from the Github repository and add it to the vendor directory in the Golang project.

Import mgo package

When using mgo in code, you need to import its package. You can write the following code at the top of the file to import the mgo package and create an alias for it.

import (

"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"

)

Querying documents in a collection

Querying MongoDB starts with querying documents in a collection. Using the Find() method of mgo.Collection, you can query the documents in the collection. Here are some basic query examples.

  1. Query all documents

If you don’t want to add any conditional filtering, you can use the Find() method to return all documents in the collection.

func getAllEmployees() ([]Employee, error) {

session := GetSession()
defer session.Close()

collection := session.DB("company").C("employees")
var employees []Employee
err := collection.Find(nil).All(&employees)

return employees, err

}

In the above code, the session.DB() method is used to open a database, and select the collection to be operated on. The Find() method returns a cursor that can be used to retrieve all documents that meet the criteria. The All() method reads all documents into the specified slice and returns an error.

  1. Conditional filtering

You can filter the returned documents by passing a conditional document. The following is an example of querying employees whose salary is greater than 1000:

func getEmployeesWithSalaryGreaterThan1000() ([]Employee, error) {

session := GetSession()
defer session.Close()

collection := session.DB("company").C("employees")
var employees []Employee
err := collection.Find(bson.M{"salary": bson.M{"$gt": 1000}}).All(&employees)

return employees, err

}

In the above code, bson.M represents a document in MongoDB. The generated condition document is

{

"salary": { "$gt": 1000 }

}

The above conditions will filter out all employees with a salary greater than $1,000. In the Find() method, pass the conditional document as a parameter. The $gt operator means greater than.

  1. Return only specific fields

Using the Select() method, you can specify the fields to be returned. As shown below:

func getEmployeeNameAndAge() ([]Employee, error) {

session := GetSession()
defer session.Close()

collection := session.DB("company").C("employees")
var employees []Employee
err := collection.Find(nil).Select(bson.M{"name": 1, "age": 1}).All(&employees)

return employees, err

}

In the above code, the Select() method is used to select the The fields returned. In this example, the name and age are returned.

Note: At least one field must be set to 1. If all fields are set to 0, the query will return an empty document.

  1. Paging

Use the Skip() and Limit() methods to paginate the results. As shown below:

func getPaginatedEmployees(page int, limit int) ([]Employee, error) {

session := GetSession()
defer session.Close()

collection := session.DB("company").C("employees")
var employees []Employee
err := collection.Find(nil).Skip((page - 1) * limit).Limit(limit).All(&employees)

return employees, err

}

In the above code, Skip() method is used to skip a specified number of documents, and the Limit() method specifies the number of documents to be returned.

Summary

This article introduces how to use mgo to query MongoDB in Golang. Query the documents in the collection by using the Find() method, and limit the documents returned by passing filtering and paging options. Use the Select() method to return only specific fields. mgo also provides other query methods and options that can be used as needed.

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

Statement:
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