3

i'm plannign to develop a module for my site. Similar to www.tastekid.com

There are users and products on my site.

For example; first user liked 2,4,56,57 products(numbers are the ids of products). Second one(user) liked 1,4,56,57 products.

I should be able to search who liked 56 and 57 both and see what is the common product ids for these users? in this case it is 4. then 1 or 2.

How can i design this? referencing or embedding ? Or any other solutoin that i don't know...

I hope it's clear my problem. Thanks.

Community
  • 1
  • 1
serkan
  • 6,885
  • 4
  • 41
  • 49

1 Answers1

3

The Mongo Documentation on Schema Design should provide you with a good starting point: http://www.mongodb.org/display/DOCS/Schema+Design There is a section on embedding and linking, as well as an example, which contains implementations of both.

Here is another question asked on Stack Overflow on the subject of embedding versus linking, that contains a very detailed answer: MongoDB relationships: embed or reference?

The Mongo Documentation titled, "Updating Data in Mongo" also contains sections on Embedding Documents and referencing documents: http://www.mongodb.org/display/DOCS/Updating+Data+in+Mongo

The above links should provide a very good understanding on the difference between embedding and referencing documents, and give you some good ideas for your schema design.

For your specific example, it looks as though you are looking to search for users who like the same products. One possible solution is to include an array of product ids that are liked by each user, like so.

> db.users.find()
db.users.save({ "_id" : 1, "name" : "Joe", "LikesProducts":[2,4,56,57] });
db.users.save({ "_id" : 2, "name" : "Jane", "LikesProducts":[1,4,56,57] });

To find which users like both products 56 and 57, you could run the following query:

> db.users.find({LikesProducts:{$all:[56,57]}})
{ "_id" : 1, "name" : "Joe", "LikesProducts" : [ 2, 4, 56, 57 ] }
{ "_id" : 2, "name" : "Jane", "LikesProducts" : [ 1, 4, 56, 57 ] }
> 

More information on the $all operator may be found in the "Advanced Queries" documentation: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24all

Your application can then determine which other products (if any) appear in the "LikesProducts" arrays for both users.

Hopefully this will give you some ideas to consider for your application. If you have any additional questions, the Community is here to help!

Community
  • 1
  • 1
Marc
  • 5,488
  • 29
  • 18