Skip to content

LautaroJayat/mongo-to-sql

Repository files navigation

Mongo To SQL!

Testing Build

A simple mongo to sql translator powered by Nodejs header

How to start

1. Clone this repo

Clone the project and then go to the root folder

git clone https://github.com/LautaroJayat/mongo-to-sql.git

cd mongo-to-sql

2. Install yarn

if you have NPM installed:

npm install --global yarn

if not, you can follow these alternative steps: https://classic.yarnpkg.com/lang/en/docs/install

3. Install all dependencies

yarn

4. Transpile the project

yarn build

5. Install package as a command line utility

yarn install:bin

# under the hood it does
# chmod +x bin/cli/index.js && npm i -g .

6. Translate a query

mongoToSql "db.myCollection.find({some: 'args'}, { fieldToProject: 1 })"

Usage

mongoToSql [options] [ command | arguments ]

Options:

  • --cool: prints a pretty title before the output
    mongoToSql --cool "db.myCollection.find({})"

Commands:

  • help : prints a help dialog with all the options
    mongoToSql help

Arguments:

  • A mongo query that will be used as input
    mongoToSql "db.myCollection.find({my: 'field'})"

Observations

String Values

When using string values, remember to use single quotes. If you try to quote using double quotes or backticks you will have an error

// this is ok
db.users.find({name: 'smith'})
// but this not
db.users.find({name: "smith"})

Command Line tips

You can use this CLI in three ways:

  1. You can introduce a a string containing a command as the first argument:
mongoToSql "db.myCollection.find({some: 'args'}, { fieldToProject: 1 })"
  1. You can interpolate the value of the first argument by using a subshell:
mongoToSql $(cat query.js)
  1. You can pipe a string directly to the command
cat query.js | mongoToSql

Bash escaping

Mongodb uses $ as a prefix for their operators, but the same character is an actual operator in bash. To avoid unexpected errors, if you are providing a string directly into the shell, remember to escape any special character:

# this will work
mongoToSql "db.users.find({age: { \$gte: 25 }, name: 'smith' })"

# this will interpret 'gte' as an env and will try to interpolate its value
mongoToSql "db.users.find({age: { $gte: 25 }, name: 'smith' })"

Uninstall

Just run:

yarn remove:bin

About

A simple mongo to sql translator powered by Nodejs

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published