johnlemon
johnlemon

Reputation: 21449

Mongodb Embedding structure and search

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

Answers (1)

Remon van Vliet
Remon van Vliet

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 :

  • Documents have a 16mb limit. If you can have enough visits to reach this limitation then you require a seperate visit collection.
  • Querying for some visits of a specific visitor is not possible. You always query top level documents so if a user has 14,000 visits and you only need a specific few you'll have to retrieve the entire document. For paging some of this can be handled by using $slice.
  • Modifying multiple visits for a single visitor with one update can be a tricky without a seperate visits collection. You can only address one array element per update through the positional operator $.

Hope that helps.

Upvotes: 2

Related Questions