Search code examples
arraysmongodbsortingmongodb-querycursor

Sort by first element in an array mongodb


I have many documents in my mongodb and I have one fields named images which is an array, users can add up to 3 image urls in that array.

It would look like this:

{
 images: ['url1', 'url2', 'url3']
 ...restOfDocument
}

I want to sort documents only by the first element in array, if it exists, I just want to sort all the documents asc or desc if there is at least one url in that array.

I tried:

{
  images: -1/1 OR  "images.0": -1/1
}

None of the above worked, I don't want to use aggregate, I just want to know if there is a way to do it using cursor sort from MongoDb.

Any help would be appreciated.


Solution

  • Using 3 sample documents:

    [
      {images: ["url1", "url2", "url3"]},
      {images: ["url7", "url2"]},
      {images: []}
    ]
    

    With a simple sorting:

    db.collection.find({}).sort({"images.0":-1})
    

    returns:

    [
      {images: ["url7", "url2"]},
      {images: ["url1", "url2", "url3"]},
      {images: []}
    ]
    

    As expected