query := bson.M{ "nombre": bson.M{"$regex": `(?i)` + search}, // me va a buscar los nombres que contengan search}我有這段代碼可以在我有名字和姓氏的數據庫中進行搜索。我希望此查詢對所有名稱包含搜索字符串的實例都有效,但我還想按姓氏添加搜索,因為如果名稱以外的其他內容出現在搜索中,查詢將被錯誤執行. 我如何實現這樣的查詢才能按名字和姓氏進行過濾?
2 回答

慕慕森
TA貢獻1856條經驗 獲得超17個贊
因為我們不知道用戶是否只會傳遞名字或姓氏的名字
search := "Carlos M"
s := strings.Split(search, " ")
s := append(s, "") // incase name is only supplied then empty string will be used for surname
query := bson.M{
"nombre": bson.M{"$regex": `(?i)` + s[0]},
"apellido": bson.M{"$regex": `(?i)` + s[1]},
}

LEATH
TA貢獻1936條經驗 獲得超7個贊
你可以使用正則表達式
query := bson.M{
"nombre": bson.M{"$regex": `\s`+surname+`\b`},
}
\s 匹配任何空白字符
\b 斷言結尾
- 2 回答
- 0 關注
- 111 瀏覽
添加回答
舉報
0/150
提交
取消