Mongodb and sorting sub array

前端 未结 2 414

Not sure if this can be done, so thought I would ask.

I have the following mongodb/s

{
 \"store\":\"abc\",
 \"offers\":[{
    \"spend\":\"100.00\",
          


        
相关标签:
2条回答
  • 2021-01-16 10:38

    Given your data structure of arrays within documents, I don't think it makes sense to do this sort in MongoDB -- Mongo will be returning entire documents (not arrays).

    If you are trying to compare offers it would probably make more sense to have a separate collection instead of an embedded array. For example, you could then find offers matching a cashback of at least $5 sorted by spend or percentage discount.

    If you are just trying to order the offers within a single document, you could do this in PHP with a usort().

    0 讨论(0)
  • 2021-01-16 11:02

    Amazingly, yes, mongodb can do this:

    // Sort ascending, by minimum percentage value in the docs' offers array.
    db.collection.find({}).sort({ 'offers.percentage': 1 });
    
    // Sort descending, by maximum percentage value in the docs' offers array.
    db.collection.find({}).sort({ 'offers.percentage': -1 });
    
    0 讨论(0)
提交回复
热议问题