Convert JSON to YAML in one command

I’ve been playing around with AWS CloudFormation recently, which supports both JSON and YAML. I prefer to use YAML, but a lot of the examples I was looking at were based in JSON. Fortunately there’s a quick way to convert a JSON file to it’s YAML equivalent.

ruby -ryaml -rjson -e 'puts YAML.dump(JSON.load(ARGF))' < linux-bastion.template > linux-bastion.yml

Can’t remember where I found it, likely StackOverflow, anyway it’s a useful command to have!

Selecting partial elements of mongo db documents

By default, when you find documents on mongo it returns the entire document, similar to what SELECT * FROM TABLE; would do in a relational world.

> db.user.find().pretty()
	"_id" : ObjectId("5217705cc2e6fc761c0b5371"),
	"userId" : "james",
	"age" : 27,
	"favouriteVideoGame" : "Skyrim"

You can retrieve partial document info by using something known as a projection (see mongo docs here). Use find() with an empty query, but specify the fields you want from the document like so:

> db.user.find({}, {userId:true})
{ "_id" : ObjectId("5217705cc2e6fc761c0b5371"), "userId" : "james" }

> db.user.find({}, {userId:true, age:true})
{ "_id" : ObjectId("5217705cc2e6fc761c0b5371"), "userId" : "james", "age" : 27 }

For the Java devs using Spring data, you can do a similar thing using the Query APIs, notably the fields().include() (docs here):

Query q = Query.query(Criteria.where("userId").is(userId));

User score = mongoTemplate.findOne(q, User.class, "user");