【问题标题】:How to execute FindOne() with logical query selector($or) in Official Go MongoDB driver? [duplicate]如何在官方 Go MongoDB 驱动程序中使用逻辑查询选择器($or) 执行 FindOne()? [复制]
【发布时间】:2020-11-09 10:01:20
【问题描述】:

我是 mongo 的初学者。我正在尝试查找将匹配"username"email 的文档。但是想不通如何实现这个条件来过滤。

这是我的文档模型:

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"`
}

还有查询:

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

err = userCollection.FindOne(context.TODO(), filter).Decode(&user)

【问题讨论】:

    标签: mongodb go mongo-go


    【解决方案1】:

    您应该使用$or$,如下所示:

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

    【讨论】:

    • 它用syntax error: unexpected {, expecting expression 抛出一个错误。
    • 末尾加分号
    【解决方案2】:

    最后这个方法对我有用。

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

    构建命令的一些信息:

    • 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.

    【讨论】:

      猜你喜欢
      • 2019-09-07
      • 1970-01-01
      • 2019-08-30
      • 1970-01-01
      • 2012-05-24
      相关资源
      最近更新 更多