Get the App
SLTechnology News&Howtos  ›  Database  › 

Basic usage tutorial of mongodb BSON

Shulou Source: shulou.com Published: 2022-06-01 03:53:53 11月09日 Update

Find Find

M: = bson.M {"create_time": bson.M {"$gte": start, "$lte": end,}, "account": account, "tag": "tag",} session.DB ("db"). C ("collect") .Find (m). Count ()

Find the data in the timestamp with the account number of account and the label of tag and count the number.

The aggregation pipeline is Pipe (pipeline interface {}) in mgo

This is similar to the pipes used in bash, where data can be processed layer by layer. Generally, the parameter passed is [] bson.M. If there is any nesting in this [] bson.M, you need to use [] bson.M.

-for example, the tag and account number are matched first.

-timestamp over a period of time

-then count the number in groups by name.

-the first three are taken in the final sort.

/ / this can be passed in Pipe m: = [] bson.M {{"$match": bson.M {"tag": "tag", "account": account, "create_time": bson.M {"$gte": start, "$lte": end}, {"$group": bson.M {"_ id": "$TagName", "count": bson.M {"$sum": 1} {"$sort": bson.M {"count":-1}}, {"$limit": 3},} / / you can get the output data var values [] result session.DB ("db"). C ("collect") .pipe (m). Pipe (& values)

A brief introduction

Package mainimport ("gopkg.in/mgo.v2"log"gopkg.in/mgo.v2/bson") type User struct {Id bson.ObjectId `bson: "_ id" `Name string `bson: "name" `PassWord string `bson: "pass_word" `Age int `bson: "age"`} func main () {db Err: = mgo.Dial ("mongodb://192.168.2.28:27017192.168.2.28:27018192.168.2.28:27019/?replicaSet=howie") if err! = nil {log.Fatalln (err)} defer db.Close () db.SetMode (mgo.Monotonic, true) c: = db.DB ("howie"). C ("person") / / insert / * c.Insert (& User {Id: bson.NewObjectId (), Name: "JK_CHENG", PassWord: "123132" Age: 2,}, & User {Id: bson.NewObjectId (), Name: "JK_WEI", PassWord: "qwer", Age: 5,}, & User {Id: bson.NewObjectId (), Name: "JK_HE", PassWord: "6666", Age: 7 }) * / var users [] User c.Find (nil). All (& users) / / query all data log.Println (users) c.FindId (users [0] .ID). All (& users) / / query log.Println (users) c.Find (bson.M {"name": "JK_WEI"}) through ID. All (& users) / / single condition query (=) log.Println (users) c.Find (bson.M {" Name ": bson.M {" $ne ":" JK_WEI "}). All (& users) / / single conditional query (! =) log.Println (users) c.Find (bson.M {" age ": bson.M {" $gt ": 5}}). All (& users) / / single conditional query (>) log.Println (users) c.Find (bson.M {" age ": bson.M {" $gte ": 5}}). All (& users) ) / / single conditional query (> =) log.Println (users) c.Find (bson.M {"age": bson.M {"$lt": 5}}) .All (& users) / / single conditional query (

Tags: Query condition data time element content field array label pipeline account learning statistics three number value parameter name added value that is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info OPPO Reno NVidia Xiaomi Docker