Schema design pattern

What would be the best approach for this scenario?

{
  "firstName": "John",
  "lastName": "Doe",
  "emergencyContact: [
      {
        "contactName": "John Smith",
        "contactNo": "123456788",
        "relationship": "Friend"
      }
  ]
}

I have a property emergency contact but I don’t need the data every time I query the user because it will only be available on the profile page should I separate the data on its own collection?? or embed it on the user?

Hello @Christian_Angelo_15065, welcome to the MongoDB Community forum!

It is correct to have the emergency contact field within the user document - that is embedded within the document. When you query the user document use a projection to retrieve the required fields from the user document and exclude other fields. For example, the following query retrieves the user’s first name and last name fields only:

db.users.findOne( 
  { firstName: "John", lastName: "Doe" }, 
  { emergencyContact: 0, _id: 0 } 
)

In the above query the { emergencyContact: 0, _id: 0 } is the projection. The emergencyContact: 0 specifies the query to exclude the field from the query output. See db.collection.findOne() - Projection for more details.

This query will return just the two fields firstName and lastName (and excludes the remaining fields) from the result document.The output will be:

{ firstName: "John", lastName: "Doe" }

1 Like

Thank you for your recommendation this is very helpful. :slight_smile:

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.