0

I am working to my very first application in Symfony2/mongodb, I have to store articles and these articles have tags, keywords and related images. At the moment I am storing these information like that:

"category" : [
    "category1",
    " category2",
    " category3"
],

but also I saw a few examples saying to do

"category" : "category1, category2, category3",

so I was guessing which one is the best way to do it?

2 Answers 2

1

It's a very bad idea to use string when you actually need an array. If you want to search documents by tag, you definitely need an array. But strings are usefull, when you need text search (for example, searching a word with it forms in sentences).

Sign up to request clarification or add additional context in comments.

Comments

0

If you use array, then you will have the following advantages:

  • You can access each item directly by index.
  • You can perform queries directly on the array using operators like $in, $nin and $elemMatch

If you use a string, then you will have to:

  • Split by , in order to do any looping
  • User text based searching in query, which is slow

One thing you need to keep in mind regarding arrays inside a MongoDB document is that it should not be too large. Arrays can get very large, and if it pushes the size of the document beyond 16 MB, it will cause issues, as 16 MB is the maximum allowed size for a single document.

In that use case, you can split off the contents of your array into a separate collection and created references.

2 Comments

what do you mean exactly for "access each item directly by index"? you mean the "_id" of the single item? Could be a problem to query a document for the array value if I have millions of small (less them 500k) documents in my collection? Thanks
By "access each item directly by index", I mean it in reference to front-end operations, like -- you can easily perform data manipulations in the controller, loop over the array directly in view etc. It shouldn't be a problem to query a document for the array value if you have millions of small documents in your collection. There was a small typo in my answer, I have corrected it. It should make more sense now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.