Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does mongo trim spaces on save?

I'm noticing that MongoDB is collapsing multiple spaces together (into one space) when saving documents to a collection. It's not just leading and trailing spaces, but any sequence of spaces - and only spaces, not all whitespace (only tested with space and tab). This happens when using the Java driver as well as the interactive mongo shell, so I'm guessing it's a "feature" of the datastore itself.

Admittedly, I don't like extraneous whitespace in my values, and I discovered this in the course of stripping them out. However, this behavior seems strange because datastores are usually expected to refrain from "cooking" or otherwise altering data beyond what's minimally necessary to conform to the underlying storage constraints. To do otherwise (where not declared to users/developers) can cause loss of data or precision. Also, why collapse the spaces instead of completely trim them at the head and tail - and why on earth collapse them between non-space characters?

    > db.test.remove()
    > db.test.save({x: "     x     \t\t\t     x     "})
    > db.test.findOne()
    { "x" : " x \t\t\t x " }

Have I mistakenly enabled this feature, or is it enabled by default? I couldn't find anything on JIRA. This seems like a bug to me, but maybe I'm just special. MongoDB version 2.0.2

like image 430
RubyTuesdayDONO Avatar asked Feb 07 '12 23:02

RubyTuesdayDONO


1 Answers

Works on 2.0.X and 2.1.X :

> db.version()
2.1.0-pre-    
> db.test.remove()
> db.test.save({x: "     x     \t\t\t     x     "})
> db.test.findOne()
{
    "_id" : ObjectId("4f3249e80b74284ac62e629d"),
    "x" : "     x     \t\t\t     x     "
}
>
like image 171
Remon van Vliet Avatar answered Oct 02 '22 16:10

Remon van Vliet