mongo-go-driver: nested OR/AND query filter

╄→гoц情女王★ 提交于 2021-02-05 08:15:26

问题


I try to create a MongoDB query filter with the nested operators (OR/AND/...). But lib requires to create a bson.D and pass bson.E elements into it. If I need to have OR/AND inside AND/OR - I need to put bson.M + bson.D inside bson.D like this:

filter := bson.M{"$and": bson.D{{"p", 10}, bson.M{"$or": bson.D{{"s", 30}, {"a", 1}}}}}

.. and of course it doesn't work: cannot use primitive.M literal (type primitive.M) as type primitive.E in slice literal. Probably the same problem will happen if later I try to use a ... in [] logics inside a bson.D

How do I create such nested queries in Go and official MongoDB driver?


回答1:


What matters is that $or requires an array, which is bson.A. Also $and is the default, you don't have to indicate that.

Your filter can be defined like this:

filter := bson.D{
    {"p", 10},
    {"$or", bson.A{
        bson.D{{"s", 30}},
        bson.D{{"a", 10}},
    }},
}

You may also use this:

filter = bson.D{
    {"p", 10},
    {"$or", bson.A{
        bson.M{"s": 30},
        bson.M{"a": 10},
    }},
}

Or this:

filter := bson.M{
    "p": 10,
    "$or": bson.A{
        bson.M{"s": 30},
        bson.M{"a": 10},
    },
}


来源:https://stackoverflow.com/questions/60969262/mongo-go-driver-nested-or-and-query-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!