2

I am a beginner in mongo with go. I am trying to find one document where "username" or email will be matched. But can't figure out the way to implement this condition to filter.

Here is my document model:

type User struct {
    Username  string    `json:"username" bson:"username"`
    Email     string    `json:"email" bson:"email"`
    Password  string    `json:"password" bson:"password"`
    CreatedAt time.Time `json:"created_at" bson:"created_at"`
    UpdatedAt time.Time `json:"updated_at" bson:"updated_at"`
}

And the query:

filter := bson.D{
   {"username", user.Username},
   {"$or": {"email", user.Email}},
}

err = userCollection.FindOne(context.TODO(), filter).Decode(&user)
Abid
  • 477
  • 1
  • 4
  • 15

2 Answers2

2

you should use $or$ as below:

filter := bson.D{
   {"$or":[{"username": user.Username},{"email": user.Email}]},}

Maryam
  • 660
  • 6
  • 19
0

Finally this method worked for me.

filter := bson.D{{
        "$or",
        bson.A{
            bson.D{
                {"username", user.Username},
            },
            bson.D{
                {"email", user.Email},
            },
        },
    }}

Some info for constructing commands:

  • D: A BSON document. This type should be used in situations where order matters, such as MongoDB commands.
  • M: An unordered map. It is the same as D, except it does not preserve order.
  • A: A BSON array.
  • E: A single element inside a D.
Abid
  • 477
  • 1
  • 4
  • 15