递归查询? [英] Recursion query?

查看:88
本文介绍了递归查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是mongodb的新手.

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

推荐答案

在某些示例中,关于哪种模式最适合您描述的访问模式类型的问题得到了回答,该问题涉及如何在MongoDB/文档数据库中表示层次结构.

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.

这将使您的示例数据:

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

由于您需要使用聚合框架来获取诸如sum之类的信息,因此对文件夹大小的查询将是:

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

这篇关于递归查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆