Data Modeling — User -> Many UUIDs -> JSON

Hello. I am wondering what document structure I should use to solve the problem below:

The data that I want to store maps a user ID to a User account. Each user account can have many “events”, and those events are stored by ID under each account (not globally). I would like to be able to quickly lookup an event by UUID without enumerating each one on every request.

Here is an example JSON User account:

{
    name: "Joe",
    events: {
        "51a9436e-b038-...": {
            startTime: ...,
            endTime: ...,
            ...
        },
        "4d3ab18f-ad40-...": {
            startTime: ...,
            endTime: ...,
            ...
        },
        ... (many more events, probably 100-1000)
    }
}

How best can I map this to MongoDB, or is there an alternative database that I should use?

Any help would be greatly appreciated!

Hello @Nate_Levin, welcome to the MongoDB Community forum!

The user’s events can be stored as an array of events. Each event is identified by a unique id field. For example,

{
  _id: <ObjectId>,
  name: <string>,
  events: [
    { id: <ObjectId>, startTime: <Date>, endTime: <Date>  , ... },
    { id: <ObjectId>, startTime: <Date>, endTime: <Date>, ... },
    //...
]

In MongoDB, most commonly, ObjectId is used to represent a unique identifier (like, the user id or event id). You can also use the UUID or any other types.

You can perform CRUD operations on the user as well as the user event data. The typical collection methods are the insertOne, findOne, updateOne and the deleteOne. There are specific operators to work with the array fields within these operations. For example, to query a specific event by its id, you can try something like this from mongosh:

// Create a user with two events
db.users.insertOne ({ name: "Tom", events: [ { id: 1, desc: "first event" }, { id: 2, desc: "second event" } ] })

// Query an event by its id, 2 for the user "Tom"
db.users.findOne( { name: "Tom", "events.id": 2 }, { "events.$": 1 )

To query by array fields efficiently, you can index the array field. Indexes on array fields are referred as Multikey Indexes.

MongoDB provides specific operators to work with array type fields, in this case the events. There are Query Operators, Projection Operators, Update Operators and Aggregation Operators which can be used with array fields. Refer the following links for usage and examples: