Search code examples
mongodbgomgo

converting MongoDB function foreach into mgo (Golang) function


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

    }
                       }

Solution

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