question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

MongoServerError: Invalid $set :: caused by :: Unrecognized expression '$sortArray

See original GitHub issue

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

6.4.7

Node.js version

16

MongoDB server version

6

Description

Is $sortArray supported?

We’re building a document tracking system and need to sort an array of changes (think of them as individual “git” commits).

Error:    MongoServerError: Invalid $set :: caused by :: Unrecognized expression '$sortArray'

Steps to Reproduce

[
{
    _id: ObjectId('631c63f50ec04fed51a687dc'),
    createdAt: "2022-09-10T10:38:24.791Z"
    changes: [
        {
            fullDocument: {
                _change: {
                    user: UUID("78a7bfaf173b460d84b34cca4aa12c03"),
                    operation: 'addArea',
                    seq: 0,
                },
            },
        },
        {
            fullDocument: {
                _change: {
                    user: UUID("78a7bfaf173b460d84b34cca4aa12c03"),
                    operation: 'updateCountry',
                    seq: 1,
                },
            },
        }
    ],
}
...
]

Code

      const rs2 = await this.changelogModel
        .aggregate([
          filter,
          {
            $set: {
              changes: {
                $sortArray: {
                  input: '$changes',
                  sortBy: { 'fullDocument._change.seq': -1 }
                }
              }
            }
          },

Expected Behavior

$sortArray is working

Edit: add createdAt timestamp to example data

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:6

github_iconTop GitHub Comments

1reaction
vnugentcommented, Sep 12, 2022

You’re right. We’re using hosted mongo on DigitalOcean and I thought we’re on v6, but it’s actually 5.0.8. Let me open a support ticket to see if it’s possible to upgrade.

Thanks so much for your time.

0reactions
AbdelrahmanHafezcommented, Sep 11, 2022

@vnugent This is probably an issue with your MongoDB server version, it does not support $sortArray yet, you probably need to update it. Please try to run the following script and see if it fails for you, and share the output in this issue.

12415.js

'use strict';
const mongoose = require('mongoose');
const assert = require('node:assert');
const { Schema } = mongoose;

const changeLogSchema = new Schema({
  bandName: String,
  tours: [{
    date: Date,
    location: String
  }]
});


const ChangeLog = mongoose.model('change_logs', changeLogSchema);

run().catch(console.error);

async function run() {
  // Arrange
  await mongoose.connect('mongodb://localhost:27017/test');
  await mongoose.connection.dropDatabase();
  const admin = new mongoose.mongo.Admin(mongoose.connection.db);
  const buildInfo = await admin.buildInfo();
  console.log('MongoDB server version', buildInfo.version);

  await ChangeLog.insertMany([
    {
      bandName: 'B',
      tours: [
        { date: new Date('2022-09-15T10:38:24.791Z'), location: 'San Francisco' },
        { date: new Date('2022-09-10T10:38:24.791Z'), location: 'Seatle' }
      ]
    },
    {
      bandName: 'A',
      tours: [
        { date: new Date('2022-09-15T10:38:24.791Z'), location: 'San Francisco' },
        { date: new Date('2022-09-10T10:38:24.791Z'), location: 'Seatle' }
      ]
    }]);
  // Act
  const docs = await ChangeLog.aggregate([
    {
      $sort: {
        bandName: 1
      }
    },
    {
      $set: {
        tours: {
          $sortArray: {
            input: '$tours',
            sortBy: {
              date: 1
            }
          }
        }
      }
    }
  ]);

  // Assert
  assert.strictEqual(docs[0].bandName, 'A');
  assert.strictEqual(docs[1].bandName, 'B');
  assert.strictEqual(docs[0].tours[0].location, 'Seatle');
  assert.strictEqual(docs[1].tours[0].location, 'Seatle');
  console.log('Assertion passed');
  console.log('Mongoose version', mongoose.version);
}

Output

$ node 12415.js
MongoDB server version 6.0.1
Assertion passed
Mongoose version 6.6.0

You can test with mongo 6 locally using Docker:

docker container run -p 27017:27017 mongo:6
Read more comments on GitHub >

github_iconTop Results From Across the Web

$reduce.in Unrecognized expression '$addToSet' - MongoDB
I am trying to use $reduce to input an array of documents return a set of values from those documents – for documents...
Read more >
How to sort nested array in MongoDB? - Stack Overflow
I was trying to use $SortArray but it doesn't recognize it. I get " Invalid $project :: caused by :: Unknown expression $sortArray...
Read more >
Projection on array with $filter #206 - Automattic/monk - GitHub
I tried it in my code but I always have Unrecognized expression '$filters' ... I got Unrecognized expression '$filters' error.
Read more >
[SERVER-9604] Improve the error message if $last operator is ...
Given the direction is for all accumulators to eventually be expressions, the example case is no longer valid example for better error message.....
Read more >
A MongoDB Aggregation Example with $match, $group & $sort
The $match operator takes the input set of documents and outputs only those that match the given criteria. It is essentially a filter....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found