Reputation: 21449
If I have a collection: Visitor and I would like to embed an array of Visits in it, then it will look something like this:
Visitor1 ->Visit 1 ->Visit 2 Visitor2 ->Visit 1 ->Visit 2
Upvotes: 0
Views: 103
Reputation: 18595
it can be efficient depending on what you have to do more often. The structure in and by itself is fine. You always getting all visits for a single visitor for "free" when you query a visitor is the biggest advantage so you get all visits for a single visitor pretty easy. It also means you don't need a visits collection which cleans up your schema.
Here are example implementations to the operations you require :
Adding a visit :
db.visitors.update({_id:<visitorId>}, {$push:{visits:<newVisit>}})
Removing a visit :
db.visitors.update({_id:<visitorId>}, {$pull:{visits:{visitId:<visitId>}})
If you meant displaying all visits of all visitors combined there's no direct way to do so currently. You can do so with either a distinct operation and some application logic to unwrap the individual arrays or use m/r. In 2.2. there will be an aggregation framework which can do that just fine.
There are some things to consider though :
Hope that helps.
Upvotes: 2