将MongoDB函数foreach转换为mgo(Golang)函数
此函数尝试通过其值更新代码匹配将MongoDB函数foreach转换为mgo(Golang)函数,mongodb,go,mgo,Mongodb,Go,Mgo,此函数尝试通过其值更新代码匹配 res集合具有品牌代码时,它将与doc.Marque进行比较,如果是这种情况,它将被品牌的值替换 这段代码在mongodbcli中工作得非常好,但正如我使用GO一样 我试图将其转换为mgo,如下所示,但它不起作用,我在mgo中未找到foreach函数,在这种情况下是否需要替换?谢谢你的帮助 db.res.find().forEach(function(doc){ var v = db.brands.findOne({code: doc.Marque}); if(
res集合
具有品牌代码
时,它将与doc.Marque
进行比较,如果是这种情况,它将被品牌的值
替换
这段代码在mongodbcli
中工作得非常好,但正如我使用GO
一样
我试图将其转换为mgo
,如下所示,但它不起作用,我在mgo
中未找到foreach函数,在这种情况下是否需要替换?谢谢你的帮助
db.res.find().forEach(function(doc){
var v = db.brands.findOne({code: doc.Marque});
if(v){
db.res.update({"Marque": doc.Marque},
{$set: {"Marque":v.value}}, {multi: true});
}
});
以下是我尝试过的:
result:=Results{}
pipe:=res.find(bson.M{}).Iter()
for pipe.Next(&result) {
brands:=brands.findOne({code: doc.Marque});
if(v){
pipe.update({"Marque": doc.Marque},
{$set: {"Marque": v.value}}, {multi: true});
}
}
访问mgo可能会帮助您了解其工作原理
其次,Golang中导出的类型/函数以大写字母开头。所以res.find
,brands.findOne
。。。如果存在此类功能,则应分别为res.Find
、brands.FineOne
// let's say you have a type like this
type myResult struct {
ID bson.ObjectId `bson:"_id"`
Marque string `bson:"Marque"`
// other fields...
}
// and another type like this
type myCode struct {
Code string `bson:"code"`
// other fields...
}
res := db.C("res")
brands := db.C("brands")
result := myResult{}
// iterate all documents
iter := res.Find(nil).Iter()
for iter.Next(&result) {
var v myCode
err := brands.Find(bson.M{"code": result.Marque}).One(&v)
if err != nil {
// maybe not found or other reason,
// it is recommend to have additional check
continue
}
query := bson.M{"_id": result.ID}
update := bson.M{"Marque": v.value}
if err = res.Update(query, update); err != nil {
// handle error
}
}
if err := iter.Close(); err != nil {
fmt.Println(err)
}
访问mgo可能会帮助您了解其工作原理
其次,Golang中导出的类型/函数以大写字母开头。所以res.find
,brands.findOne
。。。如果存在此类功能,则应分别为res.Find
、brands.FineOne
// let's say you have a type like this
type myResult struct {
ID bson.ObjectId `bson:"_id"`
Marque string `bson:"Marque"`
// other fields...
}
// and another type like this
type myCode struct {
Code string `bson:"code"`
// other fields...
}
res := db.C("res")
brands := db.C("brands")
result := myResult{}
// iterate all documents
iter := res.Find(nil).Iter()
for iter.Next(&result) {
var v myCode
err := brands.Find(bson.M{"code": result.Marque}).One(&v)
if err != nil {
// maybe not found or other reason,
// it is recommend to have additional check
continue
}
query := bson.M{"_id": result.ID}
update := bson.M{"Marque": v.value}
if err = res.Update(query, update); err != nil {
// handle error
}
}
if err := iter.Close(); err != nil {
fmt.Println(err)
}