mongo的upsert可以在数据存在的情况下进行修改操作,在数据不存在的情况下做插入新增操作,但这一次只能有一个filter以及一个update,就算使用UpdateMany方法,也是一个filter,当我们需要使用批量新增或修改的时候,每行数据的filter都不一样,每行数据的update也不一样,这时候就需要用到bulkWrite了
package main
import (
"context"
"fmt"
"smallzhoutest/mongoDBtest/util"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)
var (
client *mongo.Client
db *mongo.Database
collection *mongo.Collection
)
// Location 字段必须全为大写,小写字段不写入。。
type Location struct {
//ID string `bson:"_id"`
Uin int64 `bson:"uin"`
NodeID string `bson:"nodeID"`
X float64 `bson:"x"`
Y float64 `bson:"y"`
Z float64 `bson:"z"`
}
func init() {
// 创建连接
client = util.GetMgoCli()
//2.选择数据库 my_db
db = client.Database("music_world")
//3.选择表 my_collection
collection = db.Collection("location")
}
func main() {
upsertMany()
findMany()
}
func findMany() {
var data []Location
filter := bson.M{
"uin": bson.M{
"$gte": 1,
},
}
res, err := collection.Find(context.Background(), filter)
err = res.All(context.Background(), &data)
if err != nil {
fmt.Println("err:", err)
return
}
fmt.Println(data)
}
func upsertMany() {
locs := []Location{
{
Uin: 1,
NodeID: "id1",
X: 2,
Y: 2,
Z: 3,
},
{
Uin: 2,
NodeID: "id2",
X: 2,
Y: 2,
Z: 3,
},
{
Uin: 3,
NodeID: "id3",
X: 2,
Y: 2,
Z: 3,
},
}
var models []mongo.WriteModel
for _, v := range locs {
filter := bson.M{
"uin": bson.M{
"$eq": v.Uin,
},
"nodeID": bson.M{
"$eq": v.NodeID,
},
}
update := bson.M{
//"$set": bson.M{"uin": v.Uin, "nodeID": v.NodeID, "x": v.x, "y": v.y, "z": v.z},
"$set": v,
}
m := mongo.NewUpdateOneModel()
m.SetFilter(filter).SetUpdate(update).SetUpsert(true)
//m.SetUpsert(true)
//m.SetUpdate()
fmt.Println("v:", v)
//m.SetUpdate(v)
models = append(models, m)
}
//coll := collection.Database(KDatabaseName).Collection(KCollectionName)
if res, err := collection.BulkWrite(context.Background(), models); err != nil {
fmt.Println(err)
return
} else {
fmt.Println(res.UpsertedCount)
}
}
网友评论