I have a database field:
"sessionid": "C-dhf",
"given": "NURSE ",
"family": "SHARK",
"name": "SHARK, NURSE",
I am attempting to create a query that will query the db looking for records that family starts with "s" given name starts with "n". I am using the following to create the filter.
{"sessionid", "C-dhf"},
{"$and", bson.A{
bson.D{{"family", primitive.Regex{Pattern: "^s", Options: "i"}}},
bson.D{{"given", primitive.Regex{Pattern: "^n", Options: "i"}}},
}},
}
The filter value used in the find is:
[{sessionid C-dhf} {$and [[{family {"pattern": "^s", "options": "i"}}] [{given {"pattern": "^n", "options": "i"}}]]}]
The find is:
cursor, err := collection.Find(context.TODO(), filter, findOptions)
It returns all records in the db as though it is not even looking at the filter.
What is the proper go syntax for a multiple field wildcard query?
By default all listed conditions are in logical AND connection ($and
), so you don't need to add that:
filter := bson.D{
{"sessionid", "C-dhf"},
{"family", primitive.Regex{Pattern: "^s", Options: "i"}},
{"given", primitive.Regex{Pattern: "^n", Options: "i"}},
}
The syntax and structure you used would be appropriate if you'd wanted logical OR connection: if you'd wanted documents with given session ID, and whose family name starts with s
or given name starts with n
. That could look like this:
filter := bson.D{
{"sessionid", "C-dhf"},
{"$or", bson.A{
bson.D{{"family", primitive.Regex{Pattern: "^s", Options: "i"}}},
bson.D{{"given", primitive.Regex{Pattern: "^n", Options: "i"}}},
}},
}