"Retrieve JSON data from MongoDB without any extra spaces or formatting, also known as unpretty

In my current setup with mongodb 2.2.0, I am working on a way to display json data in a single line format instead of the "pretty" printing typically achieved with printjson() or find().pretty(). Essentially, I want the documents to be listed in json format similar to the output of db.collection.find().limit(10), but I want to accomplish this using a cursor in a javascript file like so:

var cursor = db.collection.find().sort({_id:-1}).limit(10000);
while(cursor.hasNext()){
    //printNonPrettyJson(cursor.next()); //How???!
}

print() is not suitable for this task as it produces undesirable output related to the object identifier.

The reason behind this requirement is that I intend to run the javascript file from the console and then direct the output to a file using the following command:

mongo mydatabase myjsfile.js >> /tmp/myoutput.txt

EDIT: The desired output format is:

> db.zips.find().limit(2)
{ "city" : "ACMAR", "loc" : [ -86.51557, 33.584132 ], "pop" : 6055, "state" : "A
L", "_id" : "35004" }
{ "city" : "ADAMSVILLE", "loc" : [ -86.959727, 33.588437 ], "pop" : 10616, "stat
e" : "AL", "_id" : "35005" }
>

as opposed to:

> db.zips.find().limit(2).pretty()
{
        "city" : "ACMAR",
        "loc" : [
                -86.51557,
                33.584132
        ],
        "pop" : 6055,
        "state" : "AL",
        "_id" : "35004"
}
{
        "city" : "ADAMSVILLE",
        "loc" : [
                -86.959727,
                33.588437
        ],
        "pop" : 10616,
        "state" : "AL",
        "_id" : "35005"
}
>

This specific format is not achievable through conventional methods, hence the requirement to use a cursor object.

Answer №1

let query = db.users.find().sort({date:-1}).limit(10000);
while(query.hasNext()){
    displayJsonLine(query.next());
}

Answer №2

Give display(tojson()) a shot - the MongoDB docs provide an illustration of displaying with a cursor on their site.

    var anotherCursor = db.inventory.find( { type: 'food' } );
    var anotherDocument = anotherCursor.hasNext() ? anotherCursor.next() : null;

    if (anotherDocument) {
        var anotherItem = anotherDocument.item;
        display(tojson(anotherItem));
    }

Answer №3

If you're looking for a solution, you could utilize a JavaScript hack like the following:

> 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"}

While it may not be the most elegant approach, it does get the job done.

Answer №4

By using the "sort" and "limit" options, users are able to personalize their search results. Furthermore, employing the mongoexport command with the --type=csv flag allows for exporting results directly into a CSV file, making it easily compatible for viewing in spreadsheet programs such as Excel or Google Sheets.

Answer №5

When dealing with items containing only {} brackets, splitting them based on the brackets using a regular expression is a viable solution.

This method will separate the items into {..} {..} segments, but keep in mind that it won't work if there are nested {} brackets.

var results = string.match(/\{(.|\s)*?\}/g);
if(results) for(var i=0; i<results.length; i++){
    // Output  results[i].replace(/\s+/g," ");// Removing spaces
}

Answer №6

Below is the command line code I typically utilize

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

It's uncertain if you can /sort /limit it

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it better to manage several open Mongo connections or to develop an API for making calls to the database?

Imagine you have a large network of servers all requiring access to a database. Would it be more efficient to have a direct connection to the database from each server, or to create an API for database modifications and have the servers make calls to it in ...

Utilizing a range input (slider) to extract data of importance

When dynamically adding a slider to a page using a specific string, like the one shown below: "<input type=\"range\" name=\"aName\" min=\"1\" max=\"9\"/>"; After appending it to the page with pure JavaScript, ...

AngularJS - managing routes prior to application launch

Is it okay to implement a Service within the $stateProvider for this purpose? I have read various posts on stack overflow regarding routing, but most of them seem confusing, especially for beginners. Everyone seems to have a different approach, making it ...

Running tasks in the background with Express.js after responding to the client

Operating as a basic controller, this system receives user requests, executes tasks, and promptly delivers responses. The primary objective is to shorten the response time in order to prevent users from experiencing unnecessary delays. Take a look at the ...

Utilize the latest REDUX state within a React component's function

I'm currently facing an issue in my React application where I am struggling to access the updated state from within a function. Here is a simplified version of my problem: I have a custom React Component to which I pass a variable representing the st ...

Preventing Prepend Scroll: Tips and Tricks

Adding extra content to the top of the body can be frustrating, especially if it pushes everything down as you're trying to read. Is there a way to smoothly prepend this additional content without shifting the page layout, so that it seamlessly appear ...

A guide on executing code sequentially in Node.js

Recently, I started exploring node.js and discovered its asynchronous programming feature. However, I encountered a challenge when trying to create a loop that prompts the user for input data repeatedly until the loop ends. Upon implementing the code snipp ...

Unexpected behavior observed in while loop with dual conditions

To break the while loop, I need two conditions to be met - res must not be undefined, which only happens when the status code is 200, and obj.owner needs to match a specific value I have set. Since it takes a few seconds for the owner on that page to updat ...

Dynamically getting HTML and appending it to the body in AngularJS with MVC, allows for seamless binding to a

As someone transitioning from a jQuery background to learning AngularJS, I am facing challenges with what should be simple tasks. The particular issue I am struggling with involves dynamically adding HTML and binding it to a controller in a way that suits ...

VUEJS - Link the output from my function to my sub-template

I am looking for a way to link the output of my function with the child template. methods object methods: { filterOptions(checkedValues: any) { let filtered = this.cards.filter(card => { return card.profile .map(prof ...

Executing a Javascript function from a C# WebBrowser: A Step-by-Step Guide

I am currently working on web automation using C# and a WebBrowser. There is a link that I need to 'click', however, since it triggers a Javascript function, it seems that the code needs to be executed rather than simply clicking the element (i.e ...

Is it necessary for a component to disconnect from the socket io server upon unmounting?

Is it best practice for a React component to automatically disconnect from a socket.io server when it unmounts using the useEffect hook? If so, could you provide an example of the syntax for disconnecting a React component from a socket.io server? ...

Programmatically searching individual columns in Datatables is a powerful feature that

I am currently working on creating a jQuery datatable with search functionality in each column, using the example provided on the datatables page found at https://datatables.net/examples/api/multi_filter.html Specifically, I want to be able to search the ...

Angular Application for Attaching Files to SOAP Service

I am currently utilizing soap services to pass XML data along with file attachments. While SoapUI tool works perfectly for this purpose, I want to achieve the same functionality through Angular6 in my project. Below is a snippet of my Xml code. <soap ...

The dynamic value feature in Material UI React's MenuItem is currently experiencing functionality issues

Whenever I use Select in Material UI for React, I encounter an issue where I always receive undefined when selecting from the drop-down menu. This problem seems to occur specifically when utilizing dynamic values with the MenuItem component. If I switch to ...

Simply click on the image to open it in a lightbox view with a thumbnail using jQuery

I have implemented a feature using fancybox to display images in a lightbox with thumbnail images. My requirement is that when a user clicks on an image, the clicked image should be displayed first in the lightbox and the rest of the images should not be s ...

The Authorization Header is added just once during an AJAX CORS request

I am making calls to my RESTful API from JavaScript in a CORS scenario. To send my POST authenticated request, I am utilizing JQuery. Below is an example: function postCall(requestSettings, includeAccessToken) { requestSettings.type = 'POST& ...

Unable to get the Express.js Router functioning correctly on my server, even in a basic scenario

I am encountering an issue with using express.Router(). It was not functioning correctly in my application for serving JSON from MongoDB, so I attempted to simplify the scenario. However, I am receiving a 404 Not Found error in the request. What steps shou ...

Extjs: How to Select a Node After Creating a Tree Structure

I am facing an issue with my TreePanel where I want to preselect a specific node when loading it. The nodes are fetched from a remote json file and the tree structure loads correctly. However, the selected node is not getting highlighted and Firebug is sho ...

Changing the value of a form input name after a $scope.$watch event is activated

In my AngularJS 1.4 project, I have a form input element where I am attempting to dynamically set the name attribute. <input type="email" name="{{ctrl.name}}" class="form-control" id="email" ng-minlength="5" required> The assignment of the name att ...