Custom Mongodb $limit Aggregation

Viewed 22

I need to use mongodb's $limit in the aggregation but I wanted to add a document limiting condition. But I don't know if this is possible.

Example:

db.collection.find()

{"type": "one"}
{"type": "two"}
{"type": "one"}
{"type": "three"}
{"type": "one"}
{"type": "three"}

db.collection.aggregation([ ... ])

Result I need the aggregation:

{"type": "one"}
{"type": "two"}
{"type": "one"}
{"type": "three"}
{"type": "three"}

In this case I need to limit the documents by type. And I wanted at most 2 documents of the same type. How could I do this?

Thanks in advance :)

1 Answers

Here, is one way of doing it. Instead of using $limit, group the documents by there type, and push the grouped docs in an array. Then slice that array to contain only two elements. Finally unwind the array, and return the results like this:

db.collection.aggregate([
  {
    "$group": {
      "_id": "$type",
      "docs": {
        "$push": "$$ROOT"
      }
    }
  },
  {
    "$project": {
      docs: {
        "$slice": [
          "$docs",
          2
        ]
      },
      _id: 0,
    },
  },
  {
    "$unwind": "$docs"
  },
  {
    "$replaceRoot": {
      "newRoot": "$docs"
    }
  }
])

Here's the playground [link]1

Related