[英]How to filter MongoDB documents which has a comma as part their string?
[英]How to search for documents in mongodb using GoLang mongodb driver where the value in document is a string and the filter has a slice of string?
我無法在標題中列出我的整個問題,所以這里是:
我有一段字符串var temp = []string{"abc","efg","xyz"}
現在我想在集合中搜索上面切片中的每個元素的文檔。
我知道我可以做這樣的事情:
for _, str:=range temp{
collection.Find(context.background(), bson.M{"key":str})
}
但如您所見,我將不得不發出許多查詢。
那么有沒有一種解決方案可以讓我觸發一個查詢來查找所有這些文檔,例如:
err = collection.Find(context.Background(), bson.M{"key": MY_SLICE_OF_STRING})
您可以使用:
// I'm not sure what is your struct, so I use bson.Raw for this example
// but you can parse into your struct in the loop.
resultQuery := make([]bson.Raw, 0)
// you can use bson.M if you like,
// filter := bson.M{"key": bson.M{"$in": MY_SLICE_OF_STRING}}
filter := bson.D{
{
Key: "key",
Value: bson.E{
Key: "$in",
Value: MY_SLICE_OF_STRING,
},
},
}
ctx := context.background()
cursor, err := collection.Find(ctx, filter)
if err != nil {
//Handle your error.
}
if err == nil {
// you should put defer function to close your cursor,
defer func() {
cursor.Close(ctx)
}()
for cursor.Next(ctx) {
resultQuery = append(resultQuery, cursor.Current)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.