How does MongoDB store ordered tree tables?

  mongodb, question

An ordered tree table needs to be stored in MongoDB

For example

- 1,a
 - 11,b
 - 2,c
 - 21,d
 - 22,e
 - 221,f
 - 23,g
 - 3,h

According to MongoDB official documents
There is no order for documents of the same level in the various schemes in the library. However, I need to be able to sort (reflecting the document’s top and bottom position in this level) and move and insert new data in the same level.

The plan that I can think of at present

Scheme 1, the document is written into the document in the order of this level.


  1. Every time you modify a document location, you need to modify all records at the same level in batches. Is this batch modification expensive in mongoDB?
  2. If there are multiple concurrent modifications, will the data be inconsistent?

Scheme 2: Save an array of lower-level documents in the upper-level documents


  1. How to write this query?
  2. Is this kind of query that has to be sorted every time expensive (takes up a lot of cpu and memory)?

There are many modeling methods for tree structure. Which one did you use?

If your order is natural, then indexing the path field will get the order result. In particular, the materialized path method is adopted. For example:

{ path: "1a", ...}
 { path: "1a,b",  ...}
 { path: "2c", ...}
 { path: "2c,d", ...}
 { path: "2c,e", ...}
 { path: "2c,e,f", ...}

This method can quickly query all byte points under a node, and all nodes can be sorted according to path

See the Chinese document being translated: