Home > database >  How to create a GridFSBucket and add a file in this a bucket with mongosh?
How to create a GridFSBucket and add a file in this a bucket with mongosh?

Time:07-23

I want to create a GridFS bucket with mongosh and create files in this bucket.

I tried to follow this documentation : https://www.mongodb.com/docs/drivers/node/current/fundamentals/gridfs/ But i'm stuck with errors :

> use myDb
> bucket=new mongo.GridFSBucket(db, { bucketName: 'myCustomBucket' });
ReferenceError: mongo is not defined
> var mongodb = require('mongodb');
> bucket=new mongodb.GridFSBucket(db, { bucketName: 'myCustomBucket' });
TypeError: db.collection is not a function

I assume i cannot not follow the example provided for the Node driver in mongosh. Is it possible to use GridFSBucket from mongosh ? If so, is there any working example in mongo documentation ?

CodePudding user response:

Your assumption is correct. The documentation that you link to is for the NodeJS driver. The Mongo shell uses JavaScript, but it's not NodeJS.

While not from the Mongo shell itself, there is a command line tool to work with GridFS collections. In the GridFS introduction page under "Use GridFS" you'll find mongofiles. You probably have this binary, if not, you can find it in your software repository or Mongodb.com's download page.

To connect to localhost (see the options if your MongoDB is hosted elsewhere or uses a nonstandard port) and upload a file:

# Store a file
mongofiles -d myCustomBucket put myfile.jpg

# List everything
mongofiles -d myCustomBucket list

# Find by file name with a regular expression
mongofiles -d myCustomBucket get_regex '\.jpg$'

# Or by ID
mongofiles -d myCustomBucket get_id 0123456789abcdef

# Or by filename
mongofiles -d myCustomBucket get myfile.jpg

# There's also delete_id that takes an ID rather than a filename.
mongofiles -d myCustomBucket delete myfile.jpg

To add metadata to a GridFS object, you'll need to use mongosh, I don't think mongofiles can set extra properties on an object.

  • Related