KeplerGrid guide

Sort embedded MongoDB array items with $sortArray

Sort the line items inside each document by price and SKU. Keep one result per order and compare the new order with the original.

Load the practice collection

Run once in mongosh against a development instance with an empty lineSort practice collection.

const lab = db.getSiblingDB("keplergrid_practice")
lab.lineSort.insertMany([
  { _id: "ORD-201", lines: [
    { sku: "NC", unitCents: 300 }, { sku: "AP", unitCents: 800 }, { sku: "BK", unitCents: 800 }
  ] },
  { _id: "ORD-202" }
])

In KeplerGrid, open keplergrid_practice.lineSort with a Read only connection.

Sort by decreasing price and then SKU

Use MongoDB 5.2 or later. In Aggregation → JSON, paste the pipeline and run it.

[
  { "$set": { "sortedLines": {
    "$sortArray": {
      "input": { "$ifNull": ["$lines", []] },
      "sortBy": { "unitCents": -1, "sku": 1 }
    }
  } } },
  { "$sort": { "_id": 1 } }
]

ORD-201 returns AP, BK, then NC in sortedLines. ORD-202 returns an empty array. The original lines remains available for comparison.

Choose a key that distinguishes tied items

The SKU breaks ties between items at the same price. If SKUs can repeat, add a unique line identifier to the sort when repeatability matters. The outer $sort orders the documents independently.

See how to filter or reshape a line-item array or revisit the related KeplerGrid walkthrough.