Recursion query?

流过昼夜 提交于 2020-01-01 03:47:05

问题


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


回答1:


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"}
          }
       }
]);


来源:https://stackoverflow.com/questions/14845585/recursion-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!