Search code examples
mongodbsortingmongoosemongoose-schema

Is there a way to make sure MongoDB always arranges objects in an an array in a particular order?


I am using MongoDB via mongoose.Is there a way to make sure MongoDB always arranges objects in an an array in a particular order?

Consider the schema code below:

{
    _id: '1234',
    arrayOfObjects:[{
        data:'some data'
        createdAt:'some date'      
    }]
}

I want to create a materialized view so the objects might be inserted in a random order and not in the order of their creation dates. Is there a way to make sure MongoDB always arranges objects in an an array in a particular order? Or do I have to do this when I query?


Solution

  • yes, you can use $sort operator: read more here

    a quick example:

    schema sample:

    {
      "_id": 1,
      "arrayField": [
        { "id" : 1, "someNumber" : 6 },
        { "id" : 2, "someNumber" : 9 }
      ]
    }
    

    Query sample; Sorting the arrayField by someNumber in ascending order would be like:

    update.(
       { _id: 1 },
       {
         $push: {
           arrayField: {
             $each: [ { id: 3, someNumber: 8 }, { id: 4, someNumber: 7 }, { id: 5, someNumber: 6 } ],
             $sort: { someNumber: 1 }
           }
         }
       }
    )