Dipak
Dipak

Reputation: 2308

Mongodb Sorting query on collection data

I am developing MEAN stack application involved multiple types of media (eg. Photo, Video, Web content Snapshot) and text.

I required to sorting my collection in particular order by applying sort query on specific field.

Sort order:

- 0:Text, 1:Photo, 2:Video, 3:Web-content-snapshot
- 1:Photo, 2:Video, 3:Web-content-snapshot, 0:Text
- 2:Video, 1:Photo, 3:Web-content-snapshot, 0:Text
- 3:Web-content-snapshot, 2:Video, 1: Photo, 0:Text

Collection:

var mediaSchema = new Schema({
    user_id: {type: Schema.Types.ObjectId,ref: 'User'},
    // media description
    description: {type: String}, 
    // Media type: 1: image, 2: video, 3: Web content snapshot, 0: Text
    media_type: {type: Number,default: 0,index: true},
    media_name: {type: String},
    snapshot_url: {type: String},
    snapshot_content: {type: String},
    Text: {type: String}
},
{collection: 'media'});

Kindly guide me how to apply sorting query on media_type so I can get media in above described sort order. I am using mongoose module for mongodb querying.

Upvotes: 0

Views: 647

Answers (1)

Dario
Dario

Reputation: 4035

If you want to simply order (asc/desc) by media_type you can use cursor.sort():

# MongoDB native
db.media.find().sort({media_type: 1}) # or -1

# Mongoose way
MediaModel.find().sort({media_type: 1}).exec() # or -1

But if you want to apply a custom/complex sorting criteria, in mongodb you have to do it client-side (or server side with eval()).

Because cursor.sort() (and the deprecated $orderby pipeline operator) only accepts a document object as argument.

# MongoDB shell native
db.media.find().toArray().sort(customCompare);

# Mongoose way
MediaModel.find().exec()
  .then(medias => medias.sort(customCompare))
  .then(sortedMedias => console.log(sortedMedias));

# Compare function should return <=-1 | 0 | >=1 
function customCompare(media1, media2) { 
  return media1.media_type - media2.media_type 
}

Upvotes: 2

Related Questions