What is the most efficient schema for managing the position of items in various lists within MongoDB?

When dealing with two collections, lists and items, where each item can belong to multiple lists with a custom position in each list, the question arises: which approach would be more efficient without overcomplicating things?

A: Including an array of lists and their positions within each item document like so:

/* item schema */
{
  _id: ObjectID, // itemID
  lists: [
    {
      _id: ObjectID, // the listID
      orderNr: Number, // position in that specific list
    }
  ]
}

B: Creating an additional collection called contexts to store an array of itemIDs in the desired order for each list:

/* context schema */
{
    _id: ObjectID,
    listID: ObjectID,
    items: [
        {
            _id: ObjectID, // itemID
            orderNr: Number // position of item in the list
        }
    ]
}

In my opinion, option B is preferable. By querying the list's context document using its _id field, you can retrieve a set of IDs from the items array and easily query those specific items directly via their _id fields.

On the other hand, if we consider scenario A with 5,000 items, each appearing in multiple lists with frequently changing positions, it could be quite taxing for Mongo to locate all these items based on values nested inside arrays within each item. In contrast, querying a limited number of items by their _id in option B seems more efficient as MongoDB can stop once the last matching item is found.

However, is there something about MongoDB's internal mechanisms that could make option A viable? It might require less maintenance but perhaps there's a third approach I haven't considered yet?

Answer №1

Personally, I believe that option A is the superior choice within the schema context.

However, both options will necessitate the use of the aggregation query despite the presence of an additional collection. The primary goal here is to enhance performance,

Here are some steps to achieve this:

There are various tools available to generate pagination data; I recommend utilizing tools that leverage MongoDB's native driver

One example tool for generating pagination data with just one query and the ability to perform multiple joins (lookups) is:

mongodb-pagination

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an issue with axios post requests - Error: Unable to resolve host

While working in a cli node script, I have encountered an issue with axios where the following error gets logged into the console at times: Error: getaddrinfo ENOTFOUND www.foobar.com at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:67:26) { ...

The Tri-dimensional.js StereoEffect

I'm unsure why it isn't functioning properly. I've included: var effect = new THREE.StereoEffect(renderer); effect.eyeSeparation = 10; effect.setSize(window.innerWidth, window.innerHeight); console.log("aspect ratio is " + window.innerWidt ...

Utilizing zlib Compression with Node.js in a TCP Connection

I am currently embarking on my node.js journey, delving into the world of TCP servers. My goal is to ensure that all messages sent to clients are in a compressed format, utilizing zlib for this task. Here is an example of server-side code: zlib.deflate(r ...

What makes Javascript's Math.floor the least efficient method for calculating floor values in Javascript?

Typically, I'm not a big fan of microbenchmarks. However, this particular one unveils a fascinating revelation. The findings suggest that using Math.floor is actually the SLOWEST method for calculating floor in Javascript. Surprisingly, ~~n, n|n, and ...

Error: 'socket' is inaccessible before it has been initialized, specifically in the context of electron

Trying to configure an electron app where a message is sent to the server, and the server places the value on the read-only textarea. However, upon starting the app, the following error appears in the devtools console: Uncaught ReferenceError: Cannot acc ...

Javascript's regular expression can be utilized to detect an img tag that has no specified image source (src="")

My specific need is to eliminate all img tags that do not have the attribute "img" specified within them. I attempted to accomplish this using a regular expression - content.replace(/<img[^>]*>/g,""). However, this approach removes all img tags ...

Exploring the values within a single subdocument when using findOne() [MongoDB]

I have a database filled with objects that have a structure similar to this (simplified for clarity): { "_id": "GIFT100", "price": 100, "priceHistory": [ 100, 110 ], "update": 1444183299242 } My goal is to create a query docum ...

Unlocking the Power of arrayFilters in MongoDB for Efficient Pipeline-Style Updates

Currently utilizing Mongo 4.4, I am attempting to execute an update operation with the aggregation pipeline using updateOne to modify nested array elements. To target a specific array member for updating, I include an arrayFilter in the options. However, e ...

What's preventing me from accessing children in three.js group?

Having this particular class declaration class GameManager { constructor() { this._activeObjects = new THREE.Group(); } get randomGeometry() { const geometry = new THREE.BoxGeometry(0.1, 0.1, 0.1); return geometry; } get randomMat ...

Interference + brochure + plotly - temporary clicks

I have come across a reproducible example that I found at the following link: https://bl.ocks.org/timelyportfolio/5ab450e90ee510f4df9758b9ec5a8ad0. library(sf) library(plotly) library(leaflet) library(crosstalk) library(htmltools) boroughs_data <- st_ ...

Issue with activation of onClick event in case/switch statement

Currently working on a JavaScript project to recreate the Fallout terminal game, with one of the main aspects being comparing words selected by the user to those chosen by the computer. The concept of this hacking game is reminiscent of the board game Mas ...

Order the Javascript array based on the frequency of each element's occurrence

Seeking assistance with Jquery sorting based on the number of occurrences in an array as I am new to Jquery and Javascript. Numerous sorting methods have been attempted without success. The current array in Javascript is allTypesArray = ["4", "4","2", "2 ...

When using Javascript, an error is being thrown when attempting to select a nested element, stating that it is not a function

I am facing a challenge in selecting an element within another element, specifically a button within a form. Typically, I would use jQuery to achieve this as shown below: element = $('#webform-client-form-1812 input[name="op"]'); However, due t ...

Dealing with the TokenMismatchException in Laravel when a session expires can be effectively managed by

When a session expires, users cannot log back in without refreshing the page because the _token in ajax headers has expired (also known as TokenMismatchException). I am unable to handle this exception by redirecting users to a login page because the login ...

Are there any notifications triggered when a draggable element is taken out of a droppable zone?

Within a single droppable area, there is a collection of individual Field Names that can be dragged, and a table featuring X headers, each of which can be dropped into. Initially, these headers are empty. Is there a way to detect when an item is taken out ...

Adding Array Elements to List Elements

I am facing an issue while trying to display an array of items in a list. The problem is that when I click submit, it adds all the array items to each list item instead of adding one item each time. Here is the link to JSFIDDLE: https://jsfiddle.net/b7Lw ...

Is there a way to leverage JavaScript to click on one div and modify the settings of another div simultaneously?

I am struggling with my code which has unnecessary information. <div> <div id="one" class="button"></div> <div id="two" class="button"></div> </div> <div> <div class="Home tab"> < ...

Unselecting an "all selected" checkbox

I need help with my checkbox functionality. Currently, I have a checkbox that selects all options when clicked, but if one option is deselected, the "Select All" option remains checked. Any guidance on how to address this issue would be greatly appreciated ...

What is the reason for setters being overridden rather than invoked when utilized in web components?

I am delving into the realm of creating custom tables using web components, and I'm exploring how to define properties on my custom elements using getters and setters. Here is a simple table with one column and a custom row element that includes a lin ...

What is the reason for using 'app' as the top-level directory name in React Native import statements within a project setting?

Seeking to comprehend the imports within React Native source code, specifically in a file named questionnaire.actions.js, relative to the top-level directory called lucy-app: ./src/containers/newUserOnboarding/questionnaire/questionnaire.actions.js The m ...