Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to concatenate a derived array

This is my Database schema:

enter image description here

This is retrieving the reviews sorted by creation date desc and is working:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

db.films.findOne(
        { _id: ObjectId("64d69473da87c0c91ae7c596") },
        {
          title: 1,
          reviews: {
            $sortArray: { input: "$reviews", sortBy: { creationdate: -1 } },
          },
        }
      );

I tried a test here with concatenating 2 arrays from the Database and it’s working:

db.films.findOne(
        { _id: ObjectId("64d69473da87c0c91ae7c596") },
        {
          title: 1,
          reviews: {
            $concatArrays: ["$reviews", "$reviews"],
          },
        }
      );

What I’m trying to do is combine the two, concatenate $reviews with the sorted reviews array from the first statement as follows:

db.films.findOne(
        { _id: ObjectId("64d69473da87c0c91ae7c596") },
        {
          title: 1,
          reviews: {
            $concatArrays: [
              "$reviews",
              $sortArray: { input: "$reviews", sortBy: { creationdate: -1 } },
            ],
          },
        }
      );

It isn’t working, there’s a syntax error. Could I do this? any advice?

>Solution :

there’s a syntax error

It would be helpful if you would provide that syntax error. By pasting your query into mongoplayground, we can see from this example that the error is:

Unknown type: '$sortArray: {'

This is because that second argument to $concatArrays (the one in which you are modifying the earlier array) needs to itself be an object. Wrapping it in curly brackets resolves the issue:

db.films.findOne({
  _id: ObjectId("64d69473da87c0c91ae7c596")
},
{
  title: 1,
  reviews: {
    $concatArrays: [
      "$reviews",
        $sortArray: {
          input: "$reviews",
          sortBy: {
            creationdate: -1
          }
        }
      
    ]
  }
})

Playground demonstration

It’s unclear if you want to duplicate the reviews array as is written in your question, but the answer to the question itself is "yes, you can concatenate the two arrays by resolving your syntax error."

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading