Skip to content

Instantly share code, notes, and snippets.

@officialdarnyc
Forked from debdutdeb/README.md
Last active January 21, 2022 14:48
Show Gist options
  • Save officialdarnyc/4ec8623f4a36eb1cb301d080cd6ce55c to your computer and use it in GitHub Desktop.
Save officialdarnyc/4ec8623f4a36eb1cb301d080cd6ce55c to your computer and use it in GitHub Desktop.
Exporting livechat messages from db

Livechat rooms and messages both are stored in the same collection, rocketchat_room & rocketchat_message.

To first export the livechat rooms as a json file, use mongoexport like so,

mongoexport --collection=rocketchat_room --db=rocketchat \
  --jsonArray -q='{"t": "l"}' --sort='{_id: 1}' --pretty \
  --jsonFormat=relaxed --type=json --out=livechat_rooms.json

Exporting livechat messages is a little tricky. First you need to filter out only the livechat messages from the message collection. Only way to do that is by checking the room id of that message, making sure that message belongs to a livechat room.

Copy the following to a file named, livechat_messages.js (or just download from this gist, I should've attached it 😶)

// need new collections for export
const _rocketchat_message = db.getSiblingDB('_rocketchat').getCollection('_rocketchat_message');

const rocketchat = db.getSiblingDB('rocketchat');

rocketchat.rocketchat_room.find({t: 'l'}).forEach(room =>
  rocketchat.rocketchat_message.find({rid: room._id}).forEach(msg => _rocketchat_message.insert(msg))
)

Now, run,

mongo --quiet <connection string> livechat_messages.js

Export the new collection,

mongoexport --collection=_rocketchat_message --db=_rocketchat \
  --jsonArray --sort='{rid: 1}' --pretty \
  --jsonFormat=canonical --type=json --out=livechat_messages.json

Now just delete the new database,

mongo --quiet <connection string> --eval 'db.getSibligDB("_rocketchat").dropDatabase()'
// need new collections for export
const _rocketchat_message = db.getSiblingDB('_rocketchat').getCollection('_rocketchat_message');
const rocketchat = db.getSiblingDB('rocketchat');
rocketchat.rocketchat_room.find({t: 'l'}).forEach(room =>
rocketchat.rocketchat_message.find({rid: room._id}).forEach(msg => _rocketchat_message.insert(msg))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment