Skip to content

MongoDB join field applies only the first key of a multi-key sort #18258

Open

Description

@amavisse

Describe the Bug

@payloadcms/db-mongodb applies only the first key of a join field's sort. A field configured with defaultSort: ['-featured', 'name'] behaves as '-featured' alone — documents that tie on the first key come back in _id (insertion) order instead of being ordered by the second key.

A plain find() with the identical sort is correct, so the sort itself is valid. Passing the sort at query time via joins: { myJoin: { sort: [...] } } behaves the same way, because it feeds the same code path. A single-key sort works.

The Postgres adapter builds a full ORDER BY and honours every key, so the same config produces different ordering depending on the database. Nothing warns.

Cause

packages/db-mongodb/src/utilities/buildJoinAggregation.ts, in both the polymorphic and the standard join paths:

const sort = buildSortParam({ /* … */ })
const sortProperty = Object.keys(sort)[0]! // assert because buildSortParam always returns at least 1 key.
const sortDirection = sort[sortProperty] === 'asc' ? 1 : -1

buildSortParam() returns every key; the join keeps the first and discards the rest. The comment guards against zero keys — more than one appears not to have been considered. sortProperty then flows into $sort, $sortArray and the $project stage. Still present on main.

Possible fix

$sort and $sortArray.sortBy both accept multi-key specs, so this could be a direct substitution:

const sortSpec: Record<string, 1 | -1> = {}
for (const [key, dir] of Object.entries(sort)) {
  sortSpec[key] = dir === 'asc' ? 1 : -1
}

used as $sort: sortSpec and $sortArray: { input: …, sortBy: sortSpec }, with the polymorphic $project projecting every sort key instead of one (replacing the projectSort boolean, which assumes a single key).

I haven't run this against the test suite — it's derived from reading the source and MongoDB's documented $sort / $sortArray semantics.

Possibly related

Field-level defaultSort is typed string | string[], but query-level joins[...].sort is typed plain string, so the array form needs a cast to compile there. The two entry points disagree about whether multi-key sorting is expressible, while the runtime accepts and truncates it in both.

Link to the code that reproduces this issue

https://github.com/amavisse/payload-mongo-join-sort-repro

Reproduction Steps

pnpm install
pnpm repro

No database setup needed — it starts an in-memory MongoDB. To use your own instead:

MONGODB_URI="mongodb://localhost:27017/repro" pnpm repro

The script seeds one station with eight connections (two featured, inserted in deliberately non-alphabetical order so insertion order and alphabetical order are distinguishable), then runs the same sort four ways:

(* = featured)

expected (featured first, then A-Z)          : Agira, Enna, Cacchiamo, Caltanissetta, Piazza Armerina, Sperlinga, Villadoro, Villarosa
plain find(), sort: ['-featured','name']     : Agira*, Enna*, Cacchiamo, Caltanissetta, Piazza Armerina, Sperlinga, Villadoro, Villarosa
join field, defaultSort ['-featured','name'] : Enna*, Agira*, Villadoro, Villarosa, Sperlinga, Piazza Armerina, Caltanissetta, Cacchiamo
join field, query sort ['-featured','name']  : Enna*, Agira*, Villadoro, Villarosa, Sperlinga, Piazza Armerina, Caltanissetta, Cacchiamo
join field, query sort 'name' (single key)   : Agira*, Cacchiamo, Caltanissetta, Enna*, Piazza Armerina, Sperlinga, Villadoro, Villarosa

plain find() honours both keys : YES
join field honours both keys   : NO

Expected: the join returns Agira, Enna, Cacchiamo, Caltanissetta, Piazza Armerina, Sperlinga, Villadoro, Villarosa — the same as the plain find().

Actual: featured rows are in front (first key applied) but the remaining six are in insertion order, not alphabetical. Note the featured pair is also wrong — Enna, Agira rather than Agira, Enna — so the second key is absent within the matched group too, not just in the tail.

The script exits 1 while the bug is present and 0 once it's fixed, so it can be used directly as a regression test.

Which area(s) are affected?

db: mongodb

Environment Info

Binaries:
  Node: 22.15.0
Relevant Packages:
  payload: 3.90.1
  @payloadcms/db-mongodb: 3.90.1
  @payloadcms/translations: 3.90.1
Operating System:
  Platform: win32
  Arch: x64
  Version: Windows 11 Home
  Available memory (MB): 63114
  Available CPU cores: 16

Activity

  1. added
    status: needs-triage
    validate-reproduction
    on Sep 22, 2026
  2. added
    db: mongodb
    and removed
    validate-reproduction
    on Sep 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Bugdb: mongodbstatus: needs-triagev3

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions