首页 > 解决方案 > 如何使用 ID 数组查询 mongodb

问题描述

这是戈朗。我的问题是通过 ID 进行集合搜索

我想找到几个带有 ID 数组的集合

这是文件

/*document with name brands*/
{
    first_id : "100"
    second_id : "200"
    name : "adidas",
    description: "clothing"
}
{
    first_id : "101"
    second_id : "202"
    name : "ferrari",
    description: "auto"
}

这是集合模型

type Brand struct {
    FirstID     string  `bson:"first_id" json:"first_id"`
    SecondID    string  `bson:"second_id" json:"second_id"`
    Name        *string `bson:"name" json:"name"`
    Description *string `bson:"description" json:"description"`
}

此函数执行按 ID 搜索,这就是问题所在

func searchByID(collection *mongo.Collection) {

ids := [][]string{{"100", "200"}, {"101", "202"}}

filter2 := bson.M{"first_id,second_id": ids} // This is the problem

cursor, err := collection.Find(context.Background(), filter2)

brands := []Brand{}
if err == nil {
    for cursor.Next(context.Background()) {
        brand := Brand{}
        cursor.Decode(&brand)
        brands = append(brands, brand)
    }
} else {
    print(err.Error())
}

print("print the brands")
print(brands) //Result []

}

标签: mongodbgomongodb-query

解决方案


尝试这个

filter2 := map[string]interface{}{
"first_id":  map[string]interface{}{"$in": []string{"100", "200"}},
"second_id": map[string]interface{}{"$in": []string{"101", "202"}},}
cursor, err := collection.Find(context.Background(), interface{}(filter2))

推荐阅读