du16178 2016-07-23 09:45
浏览 93
已采纳

在upsert中使用mgo聚合迭代器数据而无需拆封

First of all, I am very new to go :)

I am trying to do an aggregate + upsert in mongo using go and mgo driver.

My code looks something like this:

pipe := c.Pipe([]bson.M{{"$match": bson.M{"name":"John"}}})
iter := pipe.Iter()
resp := []bson.M{}

for iter.Next(&resp) {
     //
     // read "value.sha1" from each response
     // do a:
     // otherCollection.Upsert(bson.M{"value.sha1": mySha1}, resp)
     //
}

The response from the aggregate collection can have lot's of formats, so I can't define a struct for it.

I just need to get one of the fields from the response, which is a sha1, and update another collection with the response received, based on the sha1 condition.

Can anybody point me in the right direction?

  • 写回答

1条回答 默认 最新

  • duangeli1334 2016-07-23 20:17
    关注

    Maybe I misunderstood you but you can simply access returned documents as a map. Something like this:

    pipe := c.Pipe([]bson.M{})
    iter := pipe.Iter()
    resp := bson.M{} // not array as you are using iterator which returns single document
    
    for iter.Next(&resp) {
        otherCollection.Upsert(bson.M{"value.sha1": result["value"].(bson.M)["sha1"]}, resp)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?