Sort Sub Documents in MongoDB

后端 未结 5 1256
北恋
北恋 2020-12-17 14:52

Is there a way to sort sub documents in a mongo query?

For example:

{
  \"_id\" : ObjectId(\"4c69d19532f73ad544000001\"),
  \"content\" : \"blah bla         


        
5条回答
  •  鱼传尺愫
    2020-12-17 15:17

    Starting in Mongo 4.4, the $function aggregation operator allows applying a custom javascript function to implement behaviour not supported by the MongoDB Query Language.

    For instance, in order to sort an array of objects by one of their fields:

    // {
    //   "content": "blah blah blah",
    //   "comments": [
    //     { "author": "jim", "content": "comment content 1", "date": "07-24-1995" },
    //     { "author": "joe", "content": "comment content 2", "date": "07-24-1996" },
    //     { "author": "amy", "content": "comment content 3", "date": "09-10-1999" }
    //   ]
    // }
    db.collection.aggregate(
      { $sort: { content: 1 } }, // or whatever sort order
      { $set:
        { "comments":
          { $function: {
              body: function(comments) {
                return comments.sort((a, b) => a.date < b.date);
              },
              args: ["$comments"],
              lang: "js"
          }}
        }
      }
    )
    // {
    //   "content": "blah blah blah",
    //   "comments": [
    //     { "author": "amy", "content": "comment content 3", "date": "09-10-1999" },
    //     { "author": "joe", "content": "comment content 2", "date": "07-24-1996" },
    //     { "author": "jim", "content": "comment content 1", "date": "07-24-1995" }
    //   ]
    // }
    

    $function takes 3 parameters:

    • body, which is the function to apply, whose parameter is the array to modify.
    • args, which contains the fields from the record that the body function takes as parameter. In our case "$comments".
    • lang, which is the language in which the body function is written. Only js is currently available.

提交回复
热议问题