Multi-language attributes in MongoDB

2019-03-20 11:38发布

I'm trying to design a schema paradigm in MongoDB which would support multilingual values for variable attributes in documents.

For example, I would have a product catalog where each product may require storing its name, title or any other attribute in various languages. This same paradigm should probably hold for other locale-specific properties, such as price/currency variations

I've been considering a key-value approach where key is the language code and value is the corresponding value:

 { 
      sku: "1011",
      name: { "en": "cheese", "de": "Käse", "es": "queso", etc... },
      price: { "usd": 30.95, "eur": 20, "aud": 40, etc... }
 } 

The problem is I believe this would deny me of using indices on multilingual fields. Eventually, I'd like a generic, yet intuitive, index-able design.

Any suggestion would be appreciated, thanks.

1条回答
时光不老,我们不散
2楼-- · 2019-03-20 12:11

Wholesale recommendations over your schema design may be a bit broad a topic for discussion here. I can however suggest that you consider putting the elements you are showing into an Array of sub-documents, rather than the singular sub-document with fields for each item.

{ 
    sku: "1011",
    name: [{ "en": "cheese" }, {"de": "Käse"}, {"es": "queso"}, etc... ],
    price: [{ "usd": 30.95 }, { "eur": 20 }, { "aud": 40 }, etc... ]
} 

The main reason for this is consideration for access paths to your elements which should make things easier to query. This I went through in some detail here which may be worth your reading.

It could also be a possibility to expand on this for something like your name field:

    name: [
        { "lang": "en", "value": "cheese" },
        { "lang": "de", "value: "Käse"  },
        { "lang": "es", "value": "queso" },
        etc...
    ]

All would depend on your indexing and access requirements. It all really depends on what exactly your application needs, and the beauty of MongoDB is that it allows you to structure your documents to your needs.

P.S As to anything where you are storing Money values, I suggest you do some reading and start maybe with this post here:

MongoDB - What about Decimal type of value?

查看更多
登录 后发表回答