簡體   English   中英

在 MongoDB 查詢中搜索 2 個屬性

[英]Search on 2 properties in MongoDB query

query := bson.M{
    "nombre": bson.M{"$regex": `(?i)` + search}, // me va a buscar los nombres que contengan search
}

我有這段代碼可以在我有名字和姓氏的數據庫中進行搜索。 我希望此查詢對所有名稱包含搜索字符串的實例都有效,但我還想按姓氏添加搜索,因為如果名稱以外的其他內容出現在搜索中,查詢將被錯誤執行. 我如何實現這樣的查詢才能按名字和姓氏進行過濾?

因為我們不知道用戶是否只會傳遞名字或姓氏的名字

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]},
}

你可以使用正則表達式

query := bson.M{
        "nombre": bson.M{"$regex": `\s`+surname+`\b`},
    }

\s 匹配任何空白字符

\b 斷言結尾

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM