Petru
Petru

Reputation: 914

Use mgo aggregate iterator data in upsert without unmarshaling

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?

Upvotes: 1

Views: 486

Answers (1)

CrazyCrow
CrazyCrow

Reputation: 4235

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

Upvotes: 1

Related Questions