1

I'm trying to figure out how to push a new object to an array in Go.

Screenshot of my DB: enter image description here

I need to push a new object under actors array (where maximum size is 20 items in this array).

In Node.js I would have run { $push: { "actors": {$sort: {_id: 1}, $each: [{"name": "test"}], $slice: -20}} }

But in Go I'm not sure what is the correct syntax for it.

This is how my collection struct is defined:

type General struct {
    ID              primitive.ObjectID  `bson:"_id"`
    general         string              `bson:"general,omitempty"`
    Actors []struct{
        ID          primitive.ObjectID  `bson:"_id"`
        name        string              `bson:"name,omitempty"`
    }
}

**** EDIT ****

Regrading the generation of an ObjectId:

I've updated my code according to your answer:

update := bson.D{{"$push", bson.D{{"actors", bson.D{{"$sort", bson.D{{"_id", 1}}}, {"$each", bson.A{bson.D{{"name", "test"}, {"_id", primitive.NewObjectId()}}}}, {"$slice", -20}}}}}}

But when I run the code then I get the following error: undefined: primitive.NewObjectId (exit status 2)

If I just run fmt.Println(primitive.NewObjectID()) then I can see a new ObjectId is printed... so i'm trying to figure out why it is not working in the update query.

(I've imported "go.mongodb.org/mongo-driver/bson/primitive")

1 Answer 1

2

You can build the update document or pipeline using the bson primitives in "go.mongodb.org/mongo-driver/bson" package.

Generate a ObjectId with the NewObjectID function in the primitive package.

import (
    "fmt"
    "context"
    "go.mongodb.org/mongo-driver/bson/primitive"
)
//...

update := bson.D{{"$push", bson.D{{"actors", bson.D{{"$sort", bson.D{{"_id", 1}}}, {"$each", bson.A{bson.D{{"name", "test"}, {"_id", primitive.NewObjectID()}}}}, {"$slice", -20}}}}}}

Then run the update pipeline against your collection.

import (
    "fmt"
    "context"
    "go.mongodb.org/mongo-driver/bson"
)

//...
filter := bson.D{{"_id", 12333}}
result, err := collection.UpdateOne(context.Background(), filter, update)
Sign up to request clarification or add additional context in comments.

4 Comments

Great that's seems to work well! One more question, how do I create _id on default when inserting a new actor? thx again
@YoniMayer Glad it worked out fine. I have updated my answer to include how to generate a new ObjectId for the actor.
Thanks for your response. something is still not working correctly for me, and I get an error - I've updated my original question (please see EDIT part)
I had a typo in the function name. The function should be NewObjectID not NewObjectId

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.