How can I select a number of records per a specific field using mongodb?

前端 未结 2 545
离开以前
离开以前 2021-01-21 02:36

I have a collection of documents in mongodb, each of which have a \"group\" field that refers to a group that owns the document. The documents look like this:

{         


        
2条回答
  •  一生所求
    2021-01-21 03:26

    you need aggregation framework $group stage piped in a $limit stage... you want also to $sort the records in some ways or else the limit will have undefined behaviour, the returned documents will be pseudo-random (the order used internally by mongo)

    something like that: db.collection.aggregate([{$group:...},{$sort:...},{$limit:...}])

    here there is the documentation if you want to know more

提交回复
热议问题