首页 > 解决方案 > 查询 mongo 数据是否包含数组中的值

问题描述

假设我有一个具有这种数据结构的文档:

type Book struct {
    Title          string   `bson:"title, omitempty"`
    Tags           []string `bson:"tags, omitempty"`
}

如果我想找到一本带有“科幻”和“恐怖”标签的书(生成的书可以包含比这两个更多的标签),我的代码应该是什么样子?

谢谢你。

标签: mongodbgomongodb-query

解决方案


多一点挖掘给了我这个:

filter := bson.M{
        "tags": bson.M{
            "$all": tags,
        },
    }
collection.Find(ctx, filter)

推荐阅读