John John - 1 year ago 67
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:


Example of a document in users collection:

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


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": []

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

Right now, I am fetching the whole
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download