Home > Net >  How to push object to an existing array in MongoDB
How to push object to an existing array in MongoDB

Time:01-18

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"`
}

}

CodePudding user response:

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

update := bson.D{{"$push", bson.D{{"actors", bson.D{{"$sort", bson.D{{"_id", 1}}}, {"$each", bson.A{bson.D{{"name", "test"}}}}, {"$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)
  • Related