Predefined keys/ attributes

I am new to MongoDB and have a couple questions regarding naming keys.

I am building a Content Management System that will contain items with a variety of attributes.

End-users will have the ability to select related attributes for any given item that enters the CMS. Does anyone have recommendations for maintaining an organized selection of attributes that can be selected for a particular item?

I was imagining a JSON file that would be referenced, which would contain all available attributes that can be selected. The selected attributes would then be added to item’s document.

Again, I apologize if this is a basic question. I just want to make sure I am implementing good practices.

Hi @cc9one,

Welcome to MongoDB community!

I believe the best pattern for you is the attribute pattern:

https://www.mongodb.com/blog/post/building-with-patterns-the-attribute-pattern

The benift of this pattern is the ability to add attributes flexibility while maintaining minimum index structure with ability to effectively search on any attribute.

I recommend reading through all of our known design patterns

Thanks
Pavel

1 Like

@Pavel_Duchovny this is very helpful, thank you. I did have a “specifications” array in mind.

I do want to expand on this:

ability to add attributes flexibility

I don’t necessarily want the users to have the flexibility to create their own attributes, but rather select from a list of attributes that I have already defined. Additionally, I want to have the ability to manage (i.e. add, remove, edit) attributes from this list.

This will allow me to maintain standardization of attributes as my application grows.

Hi @cc9one,

Updating attributes in an array list is possible via indexing inner objects and using an array filter update statement:
https://docs.mongodb.com/manual/reference/operator/update/positional/#update-embedded-documents-using-multiple-field-matches

This can be used with multi : true or with bulk.find().update() if you want to update multiple user documents. Adding and removing can be done by $push,$addToSet,$pull or rewritten and stored array.

Having said that, if the list of attributes is almost fixed and users share those when those can be changed for many users at once, it might make more sense to keep attribute ids as an array in users referencing attributes collection.

I will recommend doing 2 queries where one fetch user data and attributes array and use it as a $in query or aggregation to attributes

Best
Pavel

1 Like