1

Achievement that I want got is query like this in MySQL

UPDATE FROM inbox
SET unread = unread + 1
WHERE
projectID = ? AND
userID IN ("A", "B, "C")

Is MongoDB have query IN like that in MySQL?

I have tried this in Go using https://github.com/mongodb/mongo-go-driver

_, err = m.db.Collection("inbox_counter").UpdateMany(ctx, bson.M{
     "userID":    bson.D{{"$in", userIDs}},
     "projectID": e[0].ProjectID,
}, bson.D{
     {"$inc", bson.D{{"unread", 1}}},
}, options.Update().SetUpsert(true))

But it have no effect to my collections

2
  • How does userIDs look like? Commented Jul 16, 2020 at 4:12
  • @thammada.ts userIDs is []string it is array of user id Commented Jul 16, 2020 at 10:18

1 Answer 1

1

Use bson.M{"$in": userIDs} instead of bson.D{{"$in", userIDs}} in filter and for update use bson.M{"$inc": bson.M{"unread": 1}} instead bson.D{{"$inc", bson.D{{"unread", 1}}}}

_, err = m.db.Collection("inbox_counter").UpdateMany(ctx, bson.M{
     "userID":    bson.M{"$in": userIDs},
     "projectID": e[0].ProjectID,
},bson.M{"$inc": bson.M{"unread": 1}}, options.Update().SetUpsert(true))
Sign up to request clarification or add additional context in comments.

1 Comment

I haven't tried this yet but my friend said that you can use $in for Find method only. For now I'm using BulkWrite and define UpdateOne before as []*mongo.Model. Is there different performance with your code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.