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 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现