aj3423
aj3423

Reputation: 2561

mongo golang driver remove all array items without condition

I need to remove and get all elements of an array in mongodb. I found $pull and $pullAll but they require query condition, how to remove all elements without condition?

The code not work, elements still exist after the $pull:

var UserId = 123

type Event struct {
    UserId uint64 `gorm:"uniqueIndex"`
    Array  [][]byte
}

func main() {
    var DB_NAME = "test"
    var ctx = context.Background()
    client, _ := mongo.Connect(
        ctx, options.Client().ApplyURI("mongodb://localhost"))

    col := client.Database("test").Collection(`Test`)

    { // pull items

        r := col.FindOneAndUpdate(ctx, bson.M{
            `UserId`: UserId,
        }, bson.M{
            `$pull`: bson.M{
                `Array`: nil,
            },
        }, options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.Before))

        if r.Err() != nil {
            panic(r.Err())
        }
    }
}


Edit:

I found $set': bson.M{"Array": [][]byte{}} does the job, is $pull capable of doing this? Which performance is better?

Upvotes: 1

Views: 298

Answers (1)

S H A S H A N K
S H A S H A N K

Reputation: 118

The $pull operator is a "top level" operator in update statements, so you simply have this the wrong way around:

 r := col.FindOneAndUpdate(ctx, bson.M{bson.M{"$pull": bson.M{"UserId": bson.ObjectIdHex(UserId)}}

The order of update operators is always operator first, action second.

If there is no operator at the "top-level" keys, MongoDB interprets this as just a "plain object" to update and "replace" the matched document. Hence the error about the $ in the key name.

Upvotes: 1

Related Questions