MongoDB query to store File Name and location?

To store file name and location in MongoDB, create documents with fileName and fileLocation fields. This approach is useful for file management systems, content libraries, or any application that needs to track file metadata.

Syntax

db.collection.insertOne({
    "fileName": "filename.extension",
    "fileLocation": "/path/to/file/location"
});

Sample Data

Let us create a collection with file documents using insertMany() ?

db.demo645.insertMany([
    {
        "fileName": "MongoDB Program",
        "fileLocation": "C:/users/workspace/AllMongoDBProgram/MongoDB Program"
    },
    {
        "fileName": "SumOfTwoNumbers.java",
        "fileLocation": "E:/eclipseWorkspace/AllJavaPrograms/SumOfTwoNumbers.java"
    },
    {
        "fileName": "Script.sql",
        "fileLocation": "C:/MySQLQuery/Script.sql"
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e9c78f36c954c74be91e6e8"),
        ObjectId("5e9c78f36c954c74be91e6e9"),
        ObjectId("5e9c78f46c954c74be91e6ea")
    ]
}

Query Files

Display all documents from the collection using find() method ?

db.demo645.find();
{ "_id": ObjectId("5e9c78f36c954c74be91e6e8"), "fileName": "MongoDB Program", "fileLocation": "C:/users/workspace/AllMongoDBProgram/MongoDB Program" }
{ "_id": ObjectId("5e9c78f36c954c74be91e6e9"), "fileName": "SumOfTwoNumbers.java", "fileLocation": "E:/eclipseWorkspace/AllJavaPrograms/SumOfTwoNumbers.java" }
{ "_id": ObjectId("5e9c78f46c954c74be91e6ea"), "fileName": "Script.sql", "fileLocation": "C:/MySQLQuery/Script.sql" }

Key Points

  • Use descriptive field names like fileName and fileLocation for clarity.
  • Store absolute paths to avoid confusion about file locations.
  • Consider adding additional metadata like fileSize, createdDate, or fileType.

Conclusion

MongoDB efficiently stores file metadata using simple document structure with fileName and fileLocation fields. This approach provides a foundation for building file management and tracking systems.

Updated on: 2026-03-15T03:15:31+05:30

609 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements