UCAudio
UCAudio

Reputation: 77

Is a bucket pattern in MongoDb the best way to handle large unbounded arrays?

I'm implementing social features to a MERN stack app (follow/unfollow users), and trying to come up with a good MongoDB solution for avoiding issues with potentially large unbounded arrays of followers. Specifically I'm hoping to avoid:

From everything Iv'e researched, it seems like using a bucket pattern approach is the best solution... two good articles I found on this: https://www.mongodb.com/blog/post/paging-with-the-bucket-pattern--part-1 https://www.mongodb.com/blog/post/paging-with-the-bucket-pattern--part-2

I've started to approach it like this... Follower model:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const FollowerSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: 'user',
  },
  // creating an array of followers
  followers: [
    {
      user: {
        type: Schema.Types.ObjectId,
        ref: 'user',
      },
      datefol: {
        type: Date,
        default: Date.now,
      },
    },
  ],
  count: {
    type: Number,
  },
  createdate: {
    type: Date,
    default: Date.now,
    required: true,
  },
});

module.exports = Follower = mongoose.model('follower', FollowerSchema);

Upsert in Node.js api to add a follower to an array bucket (each bucket will contain 100 followers):

const follow = await Follower.updateOne(
        { user: req.params.id, count: { $lt: 100 } },
        {
          $push: {
            followers: {
              user: req.user.id,
              datefol: Date.now(),
            },
          },
          $inc: { count: 1 },
          $setOnInsert: { user: req.params.id, createdate: Date.now() },
        },
        { upsert: true }
      );

Basically every time a follower is added, this will add them to the first bucket found that contains less than 100 followers (tracked by the count).

Is this the best approach for handling potentially large arrays? My concerns are:

Upvotes: 5

Views: 5595

Answers (1)

chefjuanpi
chefjuanpi

Reputation: 1697

The bucket pattern is not the perfect match on the case you expose.

The pattern best fits your needs is the outlier pattern https://www.mongodb.com/blog/post/building-with-patterns-the-outlier-pattern

Your case is practically the same as the example on this article.

Upvotes: 0

Related Questions