The lazy wayīecause “_id” is the problem, you can just exclude the field from the output of your query: mongo -quiet -eval "db.getSiblingDB('arotest').pokemon.find()' In my example, the only problematic field was “_id”. This is a crucial point if you need to parse your JSON with “jq”. If you give to “jq” invalid JSON data, you will get an error like this one: parse error: Invalid numeric literal at line 2, column 19 Unfortunately, for the same reason we saw with the “toArray ()” method, the function does not produce valid JSON! We will focus on that point on the next part. That is more convenient to parse with “jq”. The main difference with the “toArray()” method is that we do not get an array of JSON documents but JSON documents directly (notice the absence of the brackets in the output). Then, the “printjson” function print the record in JSON format. I will only show you my favorite: mongo -quiet -eval "db.getSiblingDB('arotest').pokemon.find().forEach(printjson)"īasically, the “forEach” function will iterate throught all records returned by the cursor. There are many ways to get JSON output with a custom function. We will see in the last part how to handle this. Looks great, but did you notice the format of the “_id” field in the output? Because ObjectId(“58f56171ee9d4bd5e610d6b7”) is not surrounded by double quotes, that is not valid JSON! (you can use the excellent jsonlint if you need to validate JSON data). Let’s give it a try with my “pokemon” collection from my “aro” database: mongo -quiet -eval "db.getSiblingDB('arotest').pokemon.find().toArray()" The “ toArray()” method is more suitable because it returns an array of JSON objects that contains all the documents from the cursor. In our case, “shellPrint()” is not possible because we want JSON format but the function return the results as strings. MongoDB provides you 2 built-in methods which allow you to return all the documents from a cursor: Ok, but how can I get JSON output from my query? Built-in methods In fact, when you run these commands, you tell MongoDB to print the cursor details, not the documents the cursor retrieves. If you are curious, you can try it by yourself). If you execute this command on your MongoDB installation, you will get an unexpected result! (I will not show the output because it is not very interesting. Or mongo -quiet -eval "print(db.getSiblingDB('mydatabase').mycollection.find())" Second part will focus on how to use “jq” to manipulate JSON data.īecause you can’t just do: mongo -quiet -eval "printjson(db.getSiblingDB('mydatabase').mycollection.find())" This part will focus on how to produce valid JSON output from your MongoDB shell using the “–eval” option. Today, I will show you how to easily deal with MongoDB shell output in your shell (bash, ksh, …) scripts.įor readybility purpose, this topic will be divided into 2 posts.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |