John John - 1 month ago 5
PHP Question

MongoDB optimal technique to store a "like" for a post

I am new to MongoDB.
I am trying to develop a simple practice project in PHP.

I have two collections as following:

users
collection

Example of a document in users collection:

{
"_id": ObjectId("57f099cf1ccbdd780b000029"),
"first_name": "Foo",
"last_name": "Bar",
"username": "foobar",
"email": "foobar@gmail.com",
"password": "$2y$10$5ec2yYQ8Xl1HH3zM6205LupR7hf/xOLLW9vU7VMYiUc317HB6p76e"
}


posts
collection

Example of a document in posts collection:

{
"_id": ObjectId("57ef7be11ccbdd4c17000029"),
"uid": ObjectId("57e6ff571ccbdd6016000029"),
"content": "Data of the post goes here!",
"time": NumberInt(1475312609),
"likes": [],
"comments": []
}


The
likes
key saves the user IDs as in array.

The problem I am facing is that, I want to show the unlike button if the user have already liked the post. In that case I have to check that if the user ID of the current user (stored in session) is in the
likes
array.

Right now, I am fetching the whole
likes
array and check for the user ID in PHP.

I was thinking that, what would be the optimal solution for this problem.

Thank you for any help!

Answer

You can manage the counter on the post collection. And the optimal to reduce time complexity solution would be to create a different collection. And user the post ID as the key and User ID as the value.

Then you can perform this operation:

db.likes.find({"post_id": "user_id"})

This will give you the result for the particular user id and post id combination.

Note: This method is good in terms of time complexity but will use memory as it saves post_id every time.