Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variable user selection

I need to create some variation for the user, so that he can select only those users for whom he specifies a category (search by category) or those who do not have the same categories as in the array (in the code you can see the array).
I used the documentation and found this answer: operator $ne

But it is not works, I get a list of all users

func (r *Mongo) User(ctx context.Context, query *domain.Query) ([]*User, error) {
    var filter interface{}
    if query.Query != "" {
        filter = bson.D{primitive.E{Key: "status", Value: true}, primitive.E{Key: "category", Value: query.Query}}
    } else {
        filter = bson.D{primitive.E{Key: "status", Value: true}}
    } - this works

    if query.OtherCategory {
        category := []string{"it", "medical", "sport"}
        filter = bson.M{"status": true, "category": bson.M{"$ne": category}}
    } - this it is not works

    cursor, err := r.col.Find(ctx, filter, opts)

    var results []*domain.User
    if err = cursor.All(ctx, &results); err != nil {
        r.logger.Error().Err(err).Msg("failed find")
        return nil, err
    }

    return results, nil
}

How to make a query to get a list of users who don’t have these (array of categories in the code) categories in the array, and their status is true?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance for the answer!

>Solution :

$ne ("not equal") will list you documents where the category field of the user is not the given array.

But this is not you want: you want to list users where the user has none of the given categories, or in other words the intersection of the user’s categories and the given categories is empty.

For this you have to use the $nin ("not in") operator: list users where the category is not in the given array. For array fields this will be checked for all array elements.

if query.OtherCategory {
    category := []string{"it", "medical", "sport"}
    filter = bson.M{"status": true, "category": bson.M{"$nin": category}}
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading