0

I'm having some problems with querying the first and last name with go and mongo, basically if I search for "Jonh " (with the whitespace) it doesn't work and "John Doe" neither, but if I search "John" or "Doe" it works.

func (user User) Prepare() bson.D {
    var filters = bson.D{}
    var arrayFilters bson.A

    if user.Search != "" {
        arrayFilters = append(arrayFilters, bson.M{"profile.firstname": bsonx.Regex(user.Search, "i")})
        arrayFilters = append(arrayFilters, bson.M{"profile.lastname": bsonx.Regex(user.Search, "i")})

        filters = append(filters, bson.E{Key: "$or", Value: arrayFilters})
    }


    filters = append(filters, bson.E{Key: "deleteddate", Value: 0})

    return filters
}

I found some solutions with aggregate + concat but couldn't really translate it to bson

Mongo document:

 "_id": {
    "$oid": ""
 },
 "email": "",
 "profile": {
    "firstname": "john",
    "lastname": "doe",
 },
Brunaine
  • 1,178
  • 2
  • 16
  • 24
  • cannot you just split the string like "Josh Doe" on space and then query for first and last name based of how match strings you get? – Jakub Dóka Apr 23 '21 at 11:26
  • @JakubDóka and if i only search for the last name (if i understood your solution) ? it needs to be an open search basically for the first and last name – Brunaine Apr 23 '21 at 11:27
  • you can make your own syntax for that like "* Doe" matches all people with Doe as last name – Jakub Dóka Apr 23 '21 at 11:29
  • What about surname-first order "Doe, John"? If it is "open search" as I understand the term, I'd expect it to return the document. Can you compile a list of searches that should work like in the test-first approach? – Alex Blex Apr 23 '21 at 12:29
  • The field `profile` is an embedded-document. See this post for details about how to query such a field: [In MongoDB, how can I find a document that is embedded?](https://stackoverflow.com/questions/65289326/in-mongodb-how-can-i-find-a-document-that-is-embedded/65289982#65289982). – prasad_ Apr 23 '21 at 12:43

0 Answers0