Hi, there are multiple issues that i encountered while working with building a SearchDefinition to run $search, let me know if i’m doing something wrong
- Can’t create equals on string SearchDefinition, for example
Builders.Search.Equals(“field”,“value”) won’t compile because of the constraint on TField
The type ‘string’ must be a non-nullable value type in order to use it as parameter ‘TField’.
as far as i understood .Search.Text is a different command and needs a different index (string and not token)
- Working with GUIDs, i see that search index is able to index UUID fields, however when using .Search.Equals(“field”, someGuid) i receive InvalidCastException, i see that the internal function supports ObjectId however as far as i understood these 2 types are not exactly the same.
Thanks
2 Likes
Hello!
It looks like you’re facing issues with SearchDefinition in $search. For string fields, use Builders.Search.Text instead of Equals, as Equals requires non-nullable value types. For GUIDs, ensure your index field type matches the type you’re querying. If you’re getting an InvalidCastException, it might be due to a type mismatch between UUID and ObjectId. Here’s a quick example:
C#
// Text search
var textSearch = Builders.Search.Text(“field”, “value”);
// GUID search
var guid = new Guid(“your-guid-here”);
var guidSearch = Builders.Search.Equals(“field”, guid);
Hope this helps!
Hi Anne, .Search.Text is different than .Search.Equals it uses a different index which is not what i intend to use.
Regarding your guid example, that won’t work as i wrote it will throw InvalidcastException
3 Likes
I am having this issue as well. In the Atlas search tester, I am able to pass in a string to match a tokenized index. But in C#, I am unable to call Equals as it rejects string. In this page: https://www.mongodb.com/docs/atlas/atlas-search/equals/ it says it accepts string if the index is token, which is what I have it set up as.
Changing to Text or Phrase does not give me the result I want that I get from Equals in the search tester
I found a workaround. You can create a BsonDocument, like this:
public BsonDocument Equals(string field, string value, double? boost = null)
{
var equalsDef = new BsonDocument
{
{
"equals",
new BsonDocument { { "path", field }, { "value", value } }
}
};
if (boost.HasValue)
{
equalsDef["equals"]["score"] = new BsonDocument
{
{
"boost",
new BsonDocument { { "value", boost } }
}
};
}
return equalsDef;
}