dpca4790 2019-08-22 15:49
浏览 252

如何使用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 []

}
  • 写回答

1条回答 默认 最新

  • dongzu0742 2019-08-23 07:04
    关注

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

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记