scalamongodbliftmongodb-scala

MongoDB - Sorting by Reference or 'Foreign Key' (Liftweb, Scala)


I have a user which contains a reference field "o" which points to an organisation:

> db.users.findOne()
{
"o" : ObjectId("4ec3548544ae1b7234548826")
}

Organisations contain a field "n":

> db.organisations.findOne()
{
    "n" : "My organization" 
}

I want a list of users sorted by o.n, preferably in Scala / Lift.


Solution

  • What you are effectively asking for is a JOIN. MongoDB has no notion of a JOIN.

    From the server's perspective, collections simply don't know about each other. Some tools abstract this away (like Morphia), but there are really only two basic ways to make this happen:

    1. Manual join: load the users, then load the organizations, merge them together and join client-side.
    2. Denormalize: store a copy of the N field inside of the users collection (and keep it in sync). This will make your query work fast, but it will complicate updates.

    This lack of JOINs is one of the fundamental MongoDB trade-offs. If this is a common query or essential query, you either have to do #1, #2 or #3: pick a different DB.