Resume and bio of the author Couple of articles related to my hobby - robotics
My impressions about immigration to Australia. In Russian only. Recipes for everyday problems solving
Linux-related posts Windows-related posts
Software-related posts A lot of info about hardware
Different tools you might find useful Posts about various web technologies
Everything that doesn't fit the rest of the menu RSS feed for this blog

Tag Cloud



Andrey Mikhalchuk’s Blog

Technoblog about life

Nov 8, 2013 How to use large / multiline text as a field in mongodb

I’m working on a project that requires storing large multiline chunks of text in MongoDB. The chunks should be inserted in the database during initial database population, so I need to enter them somewhere in db population script. Unfortunately you can’t just put something like this:

db.tests.insert( {
name: 'test',
text: 'this is
my superawesome
multiline content'
} )

Javascript/JSON do not support multiline text like this. Fortunately there are several options that made my life easier. Here they are:

  1. Use Concatenation. Something like

    db.tests.insert( {
    name: 'test1',
    text: 'this is ' +
    'my superawesome ' +
    'multiline content'
    } )

    Note that in this method even though you can enter long text it will be still single line. In order to store the text as multiline use the next method.
  2. Encode control characters

    db.tests.insert( {
    name: 'test2',
    text: "this is \nmy superawesome \nmultiline content"
    } )

    This method really stores multiple lines and you can even combine it with the previous method to make it look like multiline in your editor. Still, highly annoying, here is a better way:
  3. Read from file

    db.tests.insert( {
    name: 'test2',
    text: cat( 'my_file_with_large_multiline_content' )
    } )

    Now open file called my_file_with_large_multiline_content and put this into the file:

    this is
    my superawesome
    multiline content

    Now you can edit the file any way you want and MongoDB’s cat() will read the file contents and put its contents into your document. Yay!
  4. This post is published in How To, Tools.

No comments

No comments so far

Leave a Reply

You must be logged in to post a comment.

Site Map (c) Andrey Mikhalchuk, 2005-2008