Mongodb: sort documents by array objects

前端 未结 4 513
遇见更好的自我
遇见更好的自我 2021-01-03 23:40

I would like to return the documents in an order sorted by which holds the lowest foo.bar value (which are array objects).

I can do db.collection

4条回答
  •  误落风尘
    2021-01-04 00:18

    It seems mongo can do this.

    For example, if I have the following documents:

    { a:{ b:[ {c:1}, {c:5 } ] } }
    { a:{ b:[ {c:0}, {c:12} ] } }
    { a:{ b:[ {c:4}, {c:3 } ] } }
    { a:{ b:[ {c:1}, {c:9 } ] } }
    

    And run the following:

    db.collection.find({}).sort({ "a.b.c":1 });
    // produces:
    { a:{ b:[ {c:0}, {c:12} ] } }
    { a:{ b:[ {c:1}, {c:5 } ] } }
    { a:{ b:[ {c:1}, {c:9 } ] } }
    { a:{ b:[ {c:4}, {c:3 } ] } }
    
    db.collection.find({}).sort({ "a.b.c":-1 });
    // produces:
    { a:{ b:[ {c:0}, {c:12} ] } }
    { a:{ b:[ {c:1}, {c:9 } ] } }
    { a:{ b:[ {c:1}, {c:5 } ] } }
    { a:{ b:[ {c:4}, {c:3 } ] } }
    

    As you can see, the sort by {"a.b.c":1} takes the min of all values in the array and sorts on that, whereas the sort by {"a.b.c":-1} takes the max of all the values.

提交回复
热议问题