【问题标题】:MongoDB in Go (golang) with mgo: how to use logical operators to query?MongoDB in Go (golang) with mgo:如何使用逻辑运算符进行查询?
【发布时间】:2015-01-11 23:32:08
【问题描述】:

我想在管道中使用 mgo 在 golang 中运行以下查询。

{"key1" : 1,
 "$or" : [{"key2" : 2}, {"key3" : 2}]}

我到处找,但找不到这样的例子。我尝试了很多不同的组合,例如:

...
pipeline := []bson.M{
                     bson.M{    "$match" :  bson.M{ "key1" : 1,  
                                                   "$or" : bson.M{ "key2" : 2, "key3" : 2},
                     }
                     ...
            }

正确编译,没有找到任何东西。有什么想法吗?

提前谢谢你

【问题讨论】:

    标签: mongodb go match logical-operators mgo


    【解决方案1】:

    您的 mongo 查询可以翻译成以下内容:

    pipeline := bson.D{
        {"key1", 1},
        {"$or", []interface{}{
            bson.D{{"key2", 2}},
            bson.D{{"key3", 2}},
        }},
    }
    

    查询应该等同于 mongo 控制台中的以下内容:

    db.mycollection.find({"key1" : 1, "$or" : [{"key2" : 2}, {"key3" : 2}]})
    

    如果您希望使用无序地图,bson.M,应该是这样的:

    pipeline := bson.M{
        "key1": 1,
        "$or": []interface{}{
            bson.M{"key2": 2},
            bson.M{"key3": 2},
        },
    }
    

    【讨论】:

    • 欢迎您!你错过了数组/切片,所以关键是 []interface{}
    • 我复制粘贴了你的 bson.D 示例,我得到“异常:管道阶段规范对象必须只包含一个字段。”
    • @FuriousGeorge 您是否在FindPipe 中使用查询?该错误是一个 mongodb 错误,但我在构建聚合管道方面没有玩太多,所以我不能马上告诉你如何修复它。对不起。
    • pipe := collection.Pipe(pipeline) if error := pipe.All(&res);错误!= nil { t.Fatal(error) }
    【解决方案2】:

    go lang Mongo db 或者查询

    findQuery := bson.M{"key1" : 1}
    orQuery := []bson.M{}
    orQuery := append(orQuery, bson.M{"key2" : 2}, bson.M{"key3" : 2})
    
    findquery["$or"] = orQuery
    result := []interface{}
    err := mongo.DB.C("collectionName").find(findQuery).All(&result)
    

    【讨论】:

      猜你喜欢
      • 2020-11-05
      • 1970-01-01
      • 2015-03-31
      • 2022-01-23
      • 1970-01-01
      • 2012-05-21
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多