Search on trimmed text field

Hello guys. I want to search on a trimmed field like below we have:
available document in collection:
{“name”:" Amir M "}

x= “AmirM”
And I want to achieve document somehow with find or aggregate

Is there somebody who can help me?

You can search ignoring spaces (which is what it looks like you want) by using a collation that supports ignoring white space. You can create an index that supports that collation too.

> db.trimmed.insert({"name":" Amir M "})
> db.trimmed.find({name:"AmirM"})
> db.trimmed.find({name:"AmirM"}).collation({locale:'en', alternate:"shifted"})
{ "_id" : ObjectId("614e429b56e28a042280d2cd"), "name" : " Amir M " }
> db.trimmed.createIndex({name:1}, {collation:{locale:'en', alternate:"shifted"}})
{
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"createdCollectionAutomatically" : false,
"ok" : 1
}
> db.trimmed.explain().find({name:"AmirM"}).collation({locale:'en', alternate:"shifted"})
{
"explainVersion" : "1",
"queryPlanner" : {
	"namespace" : "test.trimmed",
	"indexFilterSet" : false,
	"parsedQuery" : {
		"name" : {
			"$eq" : "AmirM"
		}
	},
	"collation" : {
		"locale" : "en",
		"caseLevel" : false,
		"caseFirst" : "off",
		"strength" : 3,
		"numericOrdering" : false,
		"alternate" : "shifted",
		"maxVariable" : "punct",
		"normalization" : false,
		"backwards" : false,
		"version" : "57.1"
	},
	"queryHash" : "362C555E",
	"planCacheKey" : "D8682954",
	"maxIndexedOrSolutionsReached" : false,
	"maxIndexedAndSolutionsReached" : false,
	"maxScansToExplodeReached" : false,
	"winningPlan" : {
		"stage" : "FETCH",
		"inputStage" : {
			"stage" : "IXSCAN",
			"keyPattern" : {
				"name" : 1
			},
			"indexName" : "name_1",
 etc

Asya

1 Like