How to remove a document from an array?

Hi,
I already posted my db structure in another post HERE but I copy and paste everything here.

These are my structs:

type Home struct {
	ID         primitive.ObjectID `json:"id" bson:"_id"`
	Name       string             `json:"name" bson:"name"`
	Location   string             `json:"location" bson:"location"`
	Rooms      []Room             `json:"rooms" bson:"rooms"`
}

type Room struct {
	ID              primitive.ObjectID   `json:"id" bson:"_id"`
	Name            string               `json:"name" bson:"name"`
	Floor           int                  `json:"floor" bson:"floor"`
}

This is my collection:

{
		"_id": "611ed1a7e81cf2e4879a73f8",
		"name":"blablabla",
		"location":"New York",
		"rooms":[
			{
				"_id":"611ed1a7e81cf2e4879a7399",
				"name":"test1",
				"floor":3
			},
			{
				"_id":"611efbb06986120738b4092f",
				"name":"test2",
				"floor":5
			}
		]
	}

I want to REMOVE the element with _id = 611efbb06986120738b4092f using mongo-go-driver.

How can I do this?

I read this post https://www.mongodb.com/community/forums/t/remove-array-element-in-mongodb-in-go/4831 but my case is different because my array is not a string array, but it contains documents.

Thank you.

Hi,
Try this (change it to something the mongodb go library can eat…):

db.collection.updateOne({_id: "611ed1a7e81cf2e4879a73f8"}, {$pull: {rooms: {_id: "611efbb06986120738b4092f"}}})

Thanks,
Rafael,

Thank you @Rafael_Green
It’s working in this way:

filter := bson.D{primitive.E{Key: "_id", Value: objectId}}
update := bson.M{
	"$pull": bson.M{
		"rooms": bson.D{primitive.E{Key: "_id", Value: objectRid}},
	},
}
collection.UpdateOne(ctx, filter, update)
1 Like