1

I have a MongoDB record, for example, called Letter.

This letter can be sent to some group of users, so many users have an access to it.

A Letter can be sent in a context of Topic that is shared between group of users.

So, the Topic model has the following structure:

  • _id
  • name (String)
  • users_ids (Array of users ids, that can send letters withing this topic)

Also, each user can remove a letter for himself.

I have some concerns regarding how to implement/store this model with MongoDB.

Variant 1:

MongoDB record, fields:

  • _id (ObjectId)
  • topic_id (ObjectId)
  • text (String)
  • deleted_for_users_ids (Array)

When a user deletes a record then we add his ID to the deleted_for_users_ids array.

To retrieve records I use the following request:

db.letters.find({topic_id: 'X', deleted_for_users_ids: {$nin: 'user_id'}})

It's not good because we can't add an Index for 'nin' filter in MongoDB.

Variant 2:

MongoDB record, fields:

  • _id (ObjectId)
  • text (String)
  • topic_id (ObjectId)
  • accesible_for_users_ids (Array)

When a user creates a record then the accesible_for_users_ids array will be equal to the topic.user_ids array.

When a user deletes a record then we remove his ID to the deleted_for_users_ids array.

To retrieve records I use the following request:

db.letters.find({topic_id: 'X', accesible_for_users_ids: {$in: 'user_id'}})

It's better, now we can use Index because a filter 'in' can be covered by index.

But I see that indexes for array use a lot of RAM, which is not good.

====

So 2 concerns: RAM and speed.

Do you have any other ideas how to implement logic like that on MongoDB

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.