se_puede_dev
se_puede_dev

Reputation: 595

MongoDB — How to sort lookup based on matching field?

In my Mongo database, I have two collections — speakers and speeches, and I'm able to "join" them (getting a speaker's speeches) using the following code block:

// I've already found the 'speaker' in the database
db.collection('speakers').aggregate([{
    $match: { "uuid": speaker.uuid } },
    { $lookup: {
        from: "speeches",
        localField: "uuid",
        foreignField: "speaker_id",
        as: "speeches" } }
]).toArray();

It works well, but I'd like to sort the speeches array by a date field or a title field, but nothing I do seems to make it happen. None of the examples I've seen here have done what I need them to do. I've tried adding { $sort: { "speech.title": -1 } } after the $lookup block, but it did nothing. Is this even possible?

Upvotes: 2

Views: 4305

Answers (1)

s7vr
s7vr

Reputation: 75934

You can use below $lookup pipeline variant available from 3.6.

{"$lookup":{
  "from":"speeches",
  "let":{"uuid":"$uuid"},
  "pipeline":[
    {"$match":{"$expr":{"$eq":["$$uuid","$speaker_id"]}}},
    {"$sort":{"title":1}}
  ],
  "as":"speeches"
}}

Upvotes: 6

Related Questions