Yoni Mayer
Yoni Mayer

Reputation: 1238

How to push object to an existing array in MongoDB

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

Upvotes: 1

Views: 212

Answers (1)

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38982

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)

Upvotes: 2

Related Questions