一、MongoDB常见命令
> show databases;
> use my_db
> db.help
> db.createCollection("my_collection")
> show collections;
> db.my_collection.help()
> db.my_collection.insertOne({uid:1000,name:"zhangsan"})
{
"acknowledged" : true,
"insertedId" : ObjectId("6235f0bbec6a4141df0dc711")
}
> db.my_collection.find()
{ "_id" : ObjectId("6235f0bbec6a4141df0dc711"), "uid" : 1000, "name" : "zhangsan" }
> db.my_collection.createIndex({uid:1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
二、代码操作
官网:https://pkg.go.dev/github.com/mongodb/mongo-go-driver
go get go.mongodb.org/mongo-driver/mongo
2.1、连接
package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var (
database *mongo.Database
collection *mongo.Collection
)
func main() {
clientOptions := options.Client().ApplyURI("mongodb://192.168.1.210:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
database = client.Database("my_db")
collection = database.Collection("my_collection")
}
2.2、insert
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type TimePoint struct {
StartTime int64 `bson:"startTime"`
EndTime int64 `bson:"endTime"`
}
type LogRecord struct {
JobName string `bson:"jobName"`
Command string `bson:"command"`
Err string `bson:"err"`
Content string `bson:"content"`
TimePoint TimePoint `bson:"timePoint"`
}
var (
database *mongo.Database
collection *mongo.Collection
record *LogRecord
result *mongo.InsertOneResult
objectID primitive.ObjectID
err error
)
func main() {
clientOptions := options.Client().ApplyURI("mongodb://192.168.1.210:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
return
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
return
}
fmt.Println("Connected to MongoDB!")
database = client.Database("cron")
collection = database.Collection("log")
record = &LogRecord{
"job20",
"echo hello",
"",
"hello",
TimePoint{
time.Now().Unix(),
time.Now().Unix() + 10,
},
}
if result, err = collection.InsertOne(context.TODO(), record); err != nil {
log.Fatal(err)
return
}
objectID = result.InsertedID.(primitive.ObjectID)
fmt.Println(objectID.Hex())
}
2.2、查询
package main
import (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type TimePoint struct {
StartTime int64 `bson:"startTime"`
EndTime int64 `bson:"endTime"`
}
type LogRecord struct {
JobName string `bson:"jobName"`
Command string `bson:"command"`
Err string `bson:"err"`
Content string `bson:"content"`
TimePoint TimePoint `bson:"timePoint"`
}
type FindByJobName struct {
JobName string `bson:"jobName"`
}
var (
database *mongo.Database
collection *mongo.Collection
cond *FindByJobName
record *LogRecord
cursor *mongo.Cursor
err error
)
func main() {
clientOptions := options.Client().ApplyURI("mongodb://192.168.1.210:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
return
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
return
}
fmt.Println("Connected to MongoDB!")
database = client.Database("cron")
collection = database.Collection("log")
cond = &FindByJobName{JobName: "job20"}
if cursor, err = collection.Find(context.TODO(), cond); err != nil {
log.Fatal(err)
return
}
for cursor.Next(context.TODO()) {
record = &LogRecord{}
if err = cursor.Decode(record); err != nil {
log.Fatal(err)
return
}
fmt.Println(record)
}
defer cursor.Close(context.TODO())
}
2.3、删除
package main
import (
"context"
"fmt"
"log"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type TimePoint struct {
StartTime int64 `bson:"startTime"`
EndTime int64 `bson:"endTime"`
}
type LogRecord struct {
JobName string `bson:"jobName"`
Command string `bson:"command"`
Err string `bson:"err"`
Content string `bson:"content"`
TimePoint TimePoint `bson:"timePoint"`
}
type FindByJobName struct {
JobName string `bson:"jobName"`
}
type TimeBeforeCond struct {
Before int64 `bson:"$It"`
}
type DeleteCond struct {
beforeCond TimeBeforeCond `bson:"TimePoint.startTime"`
}
var (
database *mongo.Database
collection *mongo.Collection
cond *FindByJobName
record *LogRecord
cursor *mongo.Cursor
deleteCond *DeleteCond
delResult *mongo.DeleteResult
err error
)
func main() {
clientOptions := options.Client().ApplyURI("mongodb://192.168.1.210:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
return
}
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
return
}
fmt.Println("Connected to MongoDB!")
database = client.Database("cron")
collection = database.Collection("log")
deleteCond = &DeleteCond{
beforeCond: TimeBeforeCond{
Before: time.Now().Unix(),
},
}
fmt.Printf("删除条件是: %v, %T\n", deleteCond, deleteCond)
if delResult, err = collection.DeleteMany(context.TODO(), deleteCond); err != nil {
log.Fatal(err)
return
}
fmt.Printf("删除的行数: %v\n", delResult.DeletedCount)
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2021-03-20 centos7.6修改网卡名称