我需要为用户创建一些变体,以便他可以只 Select 他为其指定类别(按类别搜索)的用户或那些与数组中的类别不同的用户(在代码中可以看到数组). 我使用了文档并找到了这个答案:操作员$ne

但它不起作用,我得到了所有用户的列表

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
}

如何查询以获得数组中没有这些(代码中的类别数组)类别且其状态为True的用户列表?

推荐答案

$ne("不等于")将列出用户的category字段不是给定数组的文档.

但这不是您想要的:您希望列出用户没有任何给定类别的用户,或者换句话说,用户的类别和给定类别的交集是空的.

为此,您必须使用$nin("Not In")运算符:列出类别不在给定数组中的用户.对于数组字段,将为所有数组元素判断此选项.

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

Mongodb相关问答推荐

Spring Data MongoDB中的@ Transactions(+测试容器)

执行聚合以消除重复并获得唯一计数

错误起草的 MongoDB 聚合管道 $match 阶段

如何在 MongoDB 中对字段进行自定义排序

在 MongoDB 中加入多个集合

如何将交易列表变成 token 数量的对象?

mongoDB 过滤、排序和排名结果

MongoDB 到 Snowflake 连续加载

当属性确实存在时,为什么mongoose模型的 hasOwnProperty 返回 false?

从 PHP 打印 MongoDB 日期

mongodump 是否锁定数据库?

MongoDB:单个数据库处理程序的 >5 个打开连接

如何使用node.js http服务器从mongodb返回大量行?

mongo - Ruby连接问题

如何在 Rails 中混合使用 mongodb 和传统数据库?

mongodb: UnknownError assertion src/mongo/db/server_options_helpers.cpp:355

如何向 mongodb 2.6 添加身份验证?

如何在 golang 和 mongodb 中通过 id 查找

MongoDB 用 $type 匹配一个数组?

用 MongoDB 中的属性表示多对多关系的最佳模型