登录
首页 >  Golang >  Go问答

将条件与过滤器结合使用,将 SQL 转换为 Golang 过滤器

来源:stackoverflow

时间:2024-02-23 22:54:23 460浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《将条件与过滤器结合使用,将 SQL 转换为 Golang 过滤器》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我目前有一个有效的 .deletemany 过滤器。它删除给定数组 vids_id 的所有条目:

filter := bson.D{{Key: "_id", Value: bson.D{{Key: "$in", Value: vids}}}}
res, err := DB.Collection("data").DeleteMany(context.TODO(), filter)

现在我想增强过滤器并添加一些 $and 条件,以仅删除 _id 位于给定数组 vids 中的条目,并且(!)providerid 的值为 1234

遗憾的是,我一直不知道如何在 go 中做到这一点。对我来说,读取和编写这样的过滤器非常困难。尤其是 bson.d、bson.m 和 []bson.d 以及许多大括号等。

在 sql 中,我会编写delete from data where _id in( {list} ) andproviderid=1234;

有没有 sql 到 golang mongodb 过滤器转换器?


解决方案


尝试

filter := bson.d{
    { "$and", []interface{}{
        bson.d{{ key: "_id", value: bson.d{{ key: "$in", value: vids }}}},
        bson.d{{ "providerid", 123}},
    }},
}

根据 @volkerschmid 评论

filter := bson.D{ { Key: "$and", Value: []interface{}{ bson.D{{ Key: "_id", Value: bson.D{{ Key: "$in", Value: vids }}}}, bson.D{{ Key: "providerid", Value: 123}}, }}, }

理论要掌握,实操不能落!以上关于《将条件与过滤器结合使用,将 SQL 转换为 Golang 过滤器》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>