0

Currently I'm calling .toLower() before inserting into a collection:

site.Name = site.Name.ToLower();
collection.Insert(site);

I see an article(How to force mongo to store members in lowercase?) that forces member names to be lowercase, but can't find info on forcing the values to be lowercase.

Community
  • 1
  • 1
Alex
  • 852
  • 1
  • 10
  • 21

1 Answers1

0

Doing so, be it manually or in an automated manner, seems rather dangerous, because it's a lossy operation. There are cases when transforming data on insert is appropriate, e.g. when normalizing strings to be better searchable, but generally speaking, I'd say it's a bad idea. Transform data on read from the client or on read from the database.

An alternative is to add a computed field:

public string NormalizedName {
  get { return Name.ToLowerInvariant(); }
  set { } // also hacky,
}

Especially in string searches this can also be used to remove or replace problematic UTF-8 characters.

mnemosyn
  • 45,391
  • 6
  • 76
  • 82
  • My queries are case insensitive: sites.Where(x => x.Name.ToLower() == filter.Name.ToLower()); But, I'm trying prevent multiple copies of "www.site.com", "WWW.SITE.COM", "wWw.SiTe.CoM", etc being inserted. – Alex May 13 '15 at 13:38
  • In that case, I'd definitely recommend performing the `ToLower()` when reading the data from the client in the controller, or using the computed field to search on. LINQ `Where()` and mongodb's `$where` are slow (both can't use an index). Instead, put an index on `NormalizedName` and `Find(Builders.EQ(p => p.NormalizedName, filter.Name.ToLowerInvariant()))`. Another option is to make the class' constructor perform the conversion, i.e. `Foo(name) { this.Name = name.ToLowerInvariant() }` – mnemosyn May 13 '15 at 13:41
  • I went with a custom serializer that lowercases strings. I wanted to share it here but I can't seem to get code to format right in the comment box – Alex May 13 '15 at 18:03