简体   繁体   中英

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 on, preferably in Scala / Lift.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM