简体   繁体   中英

Sort collections of docs By the biggest embedded Doc with mongodb

I have this schema with mongoose

schema = new Schema({
    id: {
      type: String,
    },
   embedded: [embeddedSchema]
});

embeddedSchema = new Schema({
    value: {
        type: String,
    },
});

This can produce something like :

{
    "_id" : ObjectId("5454f4f1073cc3b529320f79"),
    "embedded" : [ 
        {
            "value" : 123,

        }    ,        {
            "value" : 123,

        },
        {
            "value" : 123423,

        }
    ]
}

/* 1 */
{
    "_id" : ObjectId("5454f508910ef3b82970f11d"),
    "embedded" : [ 
        {
            "value" : 1,

        }     ,       {
            "value" : 2,

        },
        {
            "value" : 9999999,

        }]
}

I would like to sort the schema collection by the biggest value of embedded doc. Which query can produce this kind of result ?

Thanks you!

When you sort descending on an array element field like value , MongoDB uses the maximum value of that field among all elements in the array.

So in this case it would be:

MyModel.find().sort('-embedded.value').exec(callback);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM