How to store and get files on mongodb?

by cali_green , in category: MySQL , 4 months ago

How to store and get files on mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by brandy , 4 months ago

@cali_green 

To store and retrieve files in MongoDB, you can use GridFS, a specification for storing large files in MongoDB. Here is how you can store and retrieve files using GridFS in MongoDB:

  1. Storing files:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
const fs = require('fs');
const mongodb = require('mongodb');

const MongoClient = mongodb.MongoClient;
const url = 'mongodb://localhost:27017';

MongoClient.connect(url, function(err, client) {
  const db = client.db('mydatabase');
  const bucket = new mongodb.GridFSBucket(db);

  const filePath = '/path/to/file.txt';
  const fileStream = fs.createReadStream(filePath);

  const uploadStream = bucket.openUploadStream('file.txt');
  fileStream.pipe(uploadStream);

  uploadStream.on('finish', function() {
    console.log('File stored successfully');
    client.close();
  });
});


  1. Retrieving files:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
const fs = require('fs');
const mongodb = require('mongodb');

const MongoClient = mongodb.MongoClient;
const url = 'mongodb://localhost:27017';

MongoClient.connect(url, function(err, client) {
  const db = client.db('mydatabase');
  const bucket = new mongodb.GridFSBucket(db);

  const downloadStream = bucket.openDownloadStreamByName('file.txt');
  const fileStream = fs.createWriteStream('/path/to/downloaded/file.txt');

  downloadStream.pipe(fileStream);

  downloadStream.on('end', function() {
    console.log('File retrieved successfully');
    client.close();
  });
});


Make sure to replace 'mongodb://localhost:27017' with your Mongo URI and 'mydatabase' with the name of your database. Also, replace the file paths accordingly in the code.


By using GridFS, you can easily store and retrieve large files in MongoDB.

Related Threads:

How to store files in session with php?
How to store and render html template files?
Where should I store private certificate files in laravel?
How to store effective text files in git?
How to store xml in mongodb?
How to store yaml file in mongodb?