dongzhan8001 2018-05-24 13:41 采纳率: 0%
浏览 153
已采纳

将MongoDB函数foreach转换为mgo(Golang)函数

This is function that tries to update the code matching by its value

the res collection as having the code of Marque it will be compared with doc.Marque if it is the case it will be replaced by the value of the marque.

This code is working perfectly in mongoDB CLI, but as i am working with GO.

I tried to convert it into mgo as you may see below but it is not working , i did not find the foreach function in mgo , is there something to be replaced with in this case ? thanks for the help

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});
     }
});

Here is what i tried :

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});

    }
                       }
  • 写回答

1条回答 默认 最新

  • dounianji7883 2018-05-25 05:02
    关注

    Visit the mgo Godoc may help you understand how it works.

    Second, exported types/functions in Golang are begin with a capital letter. So res.find, brands.findOne, ... should be res.Find, brands.FineOne respectively, if such functions exist.

    // 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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有没有整苹果智能分拣线上图像数据
  • ¥20 有没有人会这个东西的
  • ¥15 cfx考虑调整“enforce system memory limit”参数的设置
  • ¥30 航迹分离,航迹增强,误差分析
  • ¥15 Chrome Manifest扩展引用Ajax-hook库拦截请求失败
  • ¥15 用Ros中的Topic通讯方式控制小乌龟的速度,走矩形;编写订阅器代码
  • ¥15 LLM accuracy检测
  • ¥15 pycharm添加远程解释器报错
  • ¥15 如何让子窗口鼠标滚动独立,不要传递消息给主窗口
  • ¥15 如何能达到用ping0.cc检测成这样?如图