0

I am trying to do an update query like so:

    coll = client.Database("tedi").Collection("users")

    filter := bson.D{primitive.E{Key: "_id", Value: userID}}
    update := bson.D{primitive.E{Key: "$addToSet", Value: bson.D{primitive.E{Key: "listings", Value: listingID}}}}
    
    ur, err := coll.UpdateOne(context.TODO(), filter, update)
    if err != nil {
        return "", err
    }

    fmt.Println(ur.MatchedCount)
    fmt.Println(ur.UpsertedCount)
    fmt.Println(ur.ModifiedCount)
    fmt.Println(ur.UpsertedID)

I get no error back, but no update happens whatsoever so I suppose the update option is not well structured. If I structure it like so: bson.D{{"$addToSet", bson.D{{"listings", listingID}}}} as it is recommended by the documentation here: https://godoc.org/go.mongodb.org/mongo-driver/mongo#Collection.UpdateOne the IDE is giving me a warning: go.mongodb.org/mongo-driver/bson/primitive.E composite literal uses unkeyed fields

all ur.*Count variables are 0 and ur.UpsertedID is nil

I am using go1.15 Linux/amd64 and go.mongodb.org/mongo-driver v1.4.0

3
  • If ur.MatchedCount is 0, that means your filter did not match any document, it's not an issue with the update document. Commented Aug 29, 2020 at 11:36
  • I thought of that but the IDs match, I mean the one my database and the one I use to query with Commented Aug 29, 2020 at 12:01
  • You think they match, but if the MatchedCount is 0, they obviously don't. Try to provide a minimal reproducible example (provide example documents and the Go UserID). Commented Aug 29, 2020 at 12:10

1 Answer 1

1

Ok, so I found my problem. I had to pass a primitive.ObjectID instead of a string. And I did it like so:

    oid, err := primitive.ObjectIDFromHex(userID)
    if err != nil {
        return err
    }

    filter := bson.D{primitive.E{Key: "_id", Value: oid}}

The rest is the same

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.