Bart
Bart

Reputation: 27245

Recursion query?

I'm new to mongodb.

Let's say I have a "file system" hierarchy in my database:

db.directories.save({ _id: "root", directories: ["src", "lib"], files: ["config.cfg"] })
db.directories.save({ _id: "src", directories: [], files: ["file1.js", "file2.js"] })
db.directories.save({ _id: "lib", directories: [], files: [] })

db.files.save({ _id: "config.cfg", size: 2310 })
db.files.save({ _id: "file1.js", size: 5039 })
db.files.save({ _id: "file2.js", size: 1299 })

How would I get the total size of a folder?

i.e. total size of "root" directory = total size of files + total size of subdirectories

Upvotes: 2

Views: 3719

Answers (1)

Asya Kamsky
Asya Kamsky

Reputation: 42352

The question about what schema would best fit the type of access pattern you describe an answered in some example talks about how to represent a hierarchy in MongoDB/document database.

A common answer that works for a lot of different queries is where you store in each file its name, size, direct parent and array of all of its ancestors.

That would make your sample data:

db.files.save({ _id: "root"})
db.files.save({ _id: "src", parent: "root", ancestors: ["root"] } )
db.files.save({ _id: "lib", parent: "root", ancestors: ["root"]} )
db.files.save({ _id: "config.cfg", parent: "root", ancestors: ["root"], size: 2310 })
db.files.save({ _id: "file1.js", parent: "src", ancestors: ["root","src"], size: 5039 })
db.files.save({ _id: "file2.js", parent: "src", ancestors: ["root","src"], size: 1299 })

Now if you want to query for things like "Files in this directory" or "all files under this directory (including recursively)" you query:

db.files.find( { parent: "root" } )    // all files in /src directory
db.files.find( {ancestors: "root"} )   // all files under /root directory tree

Since you need to use aggregation framework to get things like sum, the query for size of folder would be:

db.files.aggregate([
       {$match:{ancestors:"src"}}, 
       {$group:{
           _id:   "src",
           total_size:  {$sum:"$size"}
          }
       }
]);

To see size of all folders which are in root folder it would be:

db.files.aggregate([
       {$match:{ancestors:"root"}}, 
       {$group:{
           _id:   "root",
           total_size:  {$sum:"$size"}
          }
       }
]);

Upvotes: 9

Related Questions