mongodb print json without whitespace i.e. unpretty json

后端 未结 6 1058
礼貌的吻别
礼貌的吻别 2020-12-30 19:52

I\'m using mongodb 2.2.0 and am trying to print json in a single line as opposed to \"pretty\" printing using printjson() or find().pretty(). i.e.

相关标签:
6条回答
  • 2020-12-30 20:23

    Here is what I use from the command line

    mongoexport -d $dbname -c $collection -q '{ "id" : -1 }'
    

    Not sure you can /sort /limit it

    0 讨论(0)
  • 2020-12-30 20:24
    var cursor = db.collection.find().sort({_id:-1}).limit(10000);
    while(cursor.hasNext()){
        printjsononeline(cursor.next());
    }
    
    0 讨论(0)
  • 2020-12-30 20:24

    You can always do a JS hack for this:

    > db.tg.find().forEach(function(doc){ print(tojson(doc).replace(/(\r\n|\n|\r|\s)/gm, '')); })
    {"_id":ObjectId("511223348a88785127a0d13f"),"a":1,"b":1,"name":"xxxxx0"}
    

    Not pretty but works

    0 讨论(0)
  • 2020-12-30 20:26

    Try print(tojson()) - there's an example of printing using a cursor in the MongoDB docs.

        var myCursor = db.inventory.find( { type: 'food' } );
        var myDocument = myCursor.hasNext() ? myCursor.next() : null;
    
        if (myDocument) {
            var myItem = myDocument.item;
            print(tojson(myItem));
        }
    
    0 讨论(0)
  • 2020-12-30 20:27

    if each item has {} brackets and there are no others then split it up on the brackets using a regular expression.

    This would split it up into {..} {..} items. But if there are nested {} it would not work.

    var res = s.match(/\{(.|\s)*?\}/g);
    if(res) for(var x=0;x<res.length;x++){
        // print  res[x].replace(/\s+/g," ");// w/o spaces
    }
    
    0 讨论(0)
  • 2020-12-30 20:35

    With "sort" and "limit" , results can be customised. with mongoexport --type=csv , result can be printed into csv file, which can be read in xls or in one line.

    0 讨论(0)
提交回复
热议问题