Search code examples
databasemongodbindexingmongodb-indexes

How to index a non unique key in mongodb?


I am creating a project related to the blogs. Let say I have a blog post and in that, I want to maintain comments and likes against a post.

How can I achieve it? I have created a collection of blog post and in the same, I have an array of comments. But if I think of long term, this might not be the best approach.

Can someone please suggest me the best way to maintain such activity?

And is it possible to index a non unique key in a schema?

Like if I want to create another collection for comments and likes, how to retrieve the comments against a blog? I can but without index it would be slow when data is too much.


Solution

  • Good afternoon, I can provide an answer to one of your questions: is it possible to index a non unique key in a schema?

    Yes. In mongosh you can use the following code:

    db.collection.createIndex({field: 1 (or -1)})
    

    This specifies a non-unique index field.

    As an added bonus, if you want to use a unique field then you can use the following code:

    db.collection.createIndex({field: 1 (or -1)}, {unique: true})
    

    Cheers