Nov 25, 2015

$limit (Aggregation) in MongoDB

This operator use to pass n documents to next pipe line where n is the specified limit.
See following example.


use Test


db.Inventory.insert(
{
"Title":"MongoDB Tutorial by codefari.com",
"ISBN":"1990987666765",
"AccessCountry":["India","China"],
})
db.Inventory.insert(
{
"Title":"SQL Server tutorial by codefari.com",
"ISBN":"9909876765476",
"AccessCountry":["USA"],
})
db.Inventory.insert(
{
"Title":"C# tutorial by codefari.com",
"ISBN":"8898877676544",
"AccessCountry":["UK"],
})
db.Inventory.find()

output


/* 0 */
{
    "_id" : ObjectId("5655b294583c040b3341b96e"),
    "Title" : "MongoDB Tutorial by codefari.com",
    "ISBN" : "1990987666765",
    "AccessCountry" : [
        "India",
        "China"
    ]
}

/* 1 */
{
    "_id" : ObjectId("5655b294583c040b3341b96f"),
    "Title" : "SQL Server tutorial by codefari.com",
    "ISBN" : "9909876765476",
    "AccessCountry" : [
        "USA"
    ]
}

/* 2 */
{
    "_id" : ObjectId("5655b294583c040b3341b970"),
    "Title" : "C# tutorial by codefari.com",
    "ISBN" : "8898877676544",
    "AccessCountry" : [
        "UK"
    ]
}

Now following query to select top 2 records only using $limit.


db.Inventory.aggregate(
    {$limit:2}
)

output


/* 0 */
{
    "result" : [
        {
            "_id" : ObjectId("5655b294583c040b3341b96e"),
            "Title" : "MongoDB Tutorial by codefari.com",
            "ISBN" : "1990987666765",
            "AccessCountry" : [
                "India",
                "China"
            ]
        },
        {
            "_id" : ObjectId("5655b294583c040b3341b96f"),
            "Title" : "SQL Server tutorial by codefari.com",
            "ISBN" : "9909876765476",
            "AccessCountry" : [
                "USA"
            ]
        }
    ],
    "ok" : 1
}