Reputation: 1190
There is an entity called «offer»
. It has many keywords. In order to avoid M:M relation (an offer may have many keywords and keywords my have many offers), I keep all keywords as embedded documents:
offers: {
title
…
country_id,
dateCreated,
keyWords: [{keyword1, keyword2, ...}]
...
}
There will be a search based on these keywords. When an offer is created, user can add keywords, which are autocompleted if already exist or added if they are new.
And the question is:
How do I update titles for keywords if they change? Ex. the user mistyped a keyword and moderator corrects it. Or there are several keywords pointing to the same entity and moderator decides to delete them and leave only one changing his title as well. And there may be thousands of offers sharing the same keyword?
One more issue:
I need to populate the autocompleter with existing keywords. Do I have to keep them also in a separate “table”?
What is the correct way? Thanks!!!
Upvotes: 2
Views: 486
Reputation: 3042
First question,
You can use array operators to achieve this goal. It requires two operations unfortunately.
As for the 2nd question, if you're going to index the keywords field, you can use distinct operator to retrieve list of keywords.
db.offer.insert({title: "Hello", keywords: ["one", "five"]});
db.offer.insert({title: "World", keywords: ["one", "three"]});
db.offer.distinct("keywords");
[ "one", "three", "five"]
If you don't have index or the collection is too huge, maintaining the list of keywords in a separate collection/document may be an option.
Upvotes: 3