mongodb - 如何使用 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 []
}
解决方案
尝试这个
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))
推荐阅读
- reactjs - 如果用户使用 react-native-otp-input 输入不正确的 otp,如何重置输入的 otp
- c++ - 概念可能会取代 C++ 中的类型特征吗?
- windows - 参数未传递给简单的 powershell 函数
- c# - Identityserver4 和组管理
- reactjs - 如何检查文件大小的大小和尺寸反应原生?
- python - 在熊猫数据框中取两个值的平均值
- java - 带有 FFmpeg 和 JavaFx 的 JavaCV 视频播放器
- php - 未找到特征“Illuminate\Notifications\Notifiable”(500 内部服务器错误)
- neural-network - 为什么我的卷积模型不学习?
- ssms - Sqlpackage 抛出错误没有详细信息