1

What I need to do is that I need to convert MongoDB query format (left of =>) that is in JSON string to corresponding SQL query WHERE clause (right of =>)

{ status: "D" }`  **=>** `WHERE status = "D"
{ status: { $in: [ "A", "D" ] } }  **=>**  WHERE status in ("A", "D")
{ $or: [ { status: "A" }, { qty: { $lt: 30 } } ] }  **=>** WHERE status = "A" OR qty < 30
{ $and: [ { status: "A" }, { qty: { $lt: 30 } } ] } **=>** WHERE status = "A" AND qty < 30

Can you please gide me any framework/library that I can use for it? Projetc is in Java language.

1
  • framework/library to convert MongoDB to SQL? I'm not sure If I understand your question correctly Commented Dec 15, 2020 at 15:22

1 Answer 1

1

You could try the npm package mongo-to-sql-converter, which was designed for this purpose.

Adapting the docs for your question:

var mongoToSqlConverter = require("mongo-to-sql-converter")

const MongoDBQuery = "db.user.find({ $or: [ { status: 'A' }, { qty: { $lt: 30 } } ] });"

const SQLQuery = mongoToSqlConverter.convertToSQL(MongoDBQuery, true)

console.log(SQLQuery)

Putting the above in a script and running with node in the terminal results in

✗ node mongo.js 

SELECT * FROM user WHERE (status = 'A' OR qty < 30);

which seems to be what you're after.

Sign up to request clarification or add additional context in comments.

3 Comments

Better learn how to write queries in MongoDB. This converter covers only the very basic functions. Stuff like NOT IN, =ANY, <>ALL or regular expressions are not converted.
The solution covers the examples provided in the question.
No. There are libraries to get node code working with java (e.g. trireme) or you could port the code to java as there is very little of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.