如何使用ID数组查询mongodb

This is golang. My problem is in the collection search by IDs

I want to find several collections with an array of IDs

This is the document

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

This is the collection model

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"`
}

This function performs the search by IDs, here is the problem

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 []

}
donglengyuan6826
donglengyuan6826 好,我已经重新考虑了这个问题
12 个月之前 回复
doufen3838
doufen3838 请提供样本数据和您已经尝试过的查询
12 个月之前 回复

1个回答



尝试一下</ p>

  filter2:= map [string] interface {} {\  n“ first_id”:map [string] interface {} {“ $ in”:[] string {“ 100”,“ 200”}},
“ second_id”:map [string] interface {} {“ $ in” :[] string {“ 101”,“ 202”}},}
cursor,错误:= collection.Find(context.Background(),interface {}(filter2))
</ code> </ pre> \ n </ div>

展开原文

原文

Try this

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))

dongwu9972
dongwu9972 这不是正确的解决方案。 与filter2相同:= bson.M {“ first_id”:bson.M {“ $ in”:[] string {“ 100”,“ 200”}},“ second_id”:bson.M {“ $ in” :[] string {“ 101”,“ 202”}}光标,错误:= collection.Find(context.Background(),filter2)
12 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐