This is my Database schema:
This is retrieving the reviews sorted by creation date desc and is working:
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
}
}
]
}
})
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."
