Skip to content

Instantly share code, notes, and snippets.

@phil294
Last active June 7, 2024 22:23
Show Gist options
  • Save phil294/6759e0214417510b3a10904e7d7b7f20 to your computer and use it in GitHub Desktop.
Save phil294/6759e0214417510b3a10904e7d7b7f20 to your computer and use it in GitHub Desktop.
Migrate MongoDB collection to SQLite DB table using Javascript/Deno
import { DB as SqliteDB } from "https://deno.land/x/sqlite/mod.ts"
import { MongoClient } from "https://deno.land/x/mongo@v0.22.0/mod.ts"
const sqlite_db = new SqliteDB("out.db")
sqlite_db.query('drop table if exists posts')
sqlite_db.query("CREATE TABLE posts (id INTEGER PRIMARY KEY AUTOINCREMENT, message TEXT)")
const client = new MongoClient()
await client.connect("mongodb://localhost:27017")
const mongo_db = client.database("my-db")
console.log('migrate posts...')
const posts_count = await mongo_db.collection("post").count()
await mongo_db.collection("post").find().forEach((post, i) => {
if(i % 1000 == 0)
console.log(Math.round(i/posts_count*100*100)/100 + ' %')
sqlite_db.query("INSERT INTO posts (id, message) VALUES (?, ?)", [post.post_id, post.message])
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment