The simplest way to explain my situation is with standard filesystem structure which is close to what I want to accomplish:
Folder A
- Folder A2
-- File 1
-- File 2
- File 3
Folder B
- Folder B2
- Folder B3
-- File 4
Folder has fields:
- _id
- parents (in my case there can actually be multiple!)
File has fields
- _id
- targetFolder
So, basically a file could be very deep in the hierarchy.
How do I search and structure my DB efficiently so that I can have deep folder hierarchies, with any of them having files.
I want to be able to do a query that returns every file under e.g. Folder A. How could I do this?
I recommend the MongoDb official documentation of this topic. Storing trees in database is non trivial and every solution have its pro and cons. I experienced successfully materialized paths model, which is very efficient on hierachy search but expensive on tree modification because you have to update every descendant node.
Not store them as a tree in mongo, at all! Like Lucas said, here is a good explanation on how you do it. But your problem is that you need a chained join from the root to Folder A. You could do something like:
{ _id, name, type, parent: { grandparent : { parentOfGrandparent : {..........
So to search for all files of Folder A you search for all files that parent is "Folder A". I think this will work:
db.files.find( { parent : { "Folder A : { $exists: true } } } );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With