0

I have the follwing schema:

  var VisionsystemSchema = new mongoose.Schema({
  linenumber: {
    type: String,
    index: true,
    unique: true
  },
  name: String,
  rois: [
    {
      name: String,
      history: [Date, Number]
    }
  ]
});

for each element in rois array i have an array of history values with a [date,number] tuple. how can i order the history array by its Date first element?

Rui Sebastião
  • 855
  • 1
  • 18
  • 36

1 Answers1

2

You can use the below aggregation query.

$unwind the rois array followed by sorting the docs by first element and $group back on _id to get the sorted array.

db.col.aggregate([
  {"$unwind":"$rois"},
  {"$sort":{"rois.history.0":-1}},
  {"$group":{"_id":"$_id","rois":{"$push":"$rois.history"}}}
])
s7vr
  • 73,656
  • 11
  • 106
  • 127