Is it better to separate Account and Session into two collection, or have a list of sessions in the Account collection?

Hi!

When my user connects to their account, I create a session token that is stored in the database and used to identify them (pretty standard stuff).

I’m coming from a relational database so my thinking is biased, and I was wondering if it was better to separate the Session and Account collection, or if it made more sense to have a “sessions” list in the Account object.

In one case, I’ll need to run two queries to load the account (first the session, and ensure it’s a valid one, then, the account). On the other, I will have to filter by a sub-object (“sessions.token”) and it might be slower.

Note that a user might have many sessions (from different computers/browser)

Is there any best way to do this approach?

Thanks for your help!

Hello @Cyril_N, welcome to the MongoDB Community forum!

The data is the user’s account and the related sessions - and a user can have multiple session objects. This is a one-to-many relationship. This can be modeled as follows:

{
  accountId: "some_value",
  accountName: "...",
  sessions: [
      { sessionId: 12, token: "abc", anotherField: "xyz09" },
      { sessionId: 9, token: "fff", anotherField: "qw66" },
      ...
  ]
}

You can query on the account information or on any of the session information. You can index on the account and session fields for faster access.

Also see, Data Modeling Introduction for MongoDB data.

1 Like

Hi Prasad, thank you for the welcoming :slight_smile:

So you’d recommend to go with the sessions array in the account. This doesn’t change anything in term of speed? (looking up inside an array for every accounts) instead of a flat Session | Account ?

(I’ll go read the Data Modeling intro :slight_smile: )

Hello @Cyril_N, first of all you will benefit from accessing a single document and get the account and the session info with a single read. And, MongoDB Query Language (MQL) and Aggregation Framework has various operators to perform CRUD operations on the array data efficiently. As long as you have a finite number of sessions within the array it is fine; note that a MongoDB document size can be up to maximum 16 MB (and that is a lot of storage).