Search code examples
phpmongodbfieldlimit

MongoDB PHP Limit the returning values of a field


{
    name : "name 1",
    field : [
        {
            random:"value 1",
            random2:"second value"
        }
        {
            random:"value 2",
            random2:"second value 2"
        }
        {
            random:"value 3",
            random2:"second value 3"
        }
        {
            random:"value 4",
            random2:"second value 4"
        }
    ]
}
{
    name : "name 2",
    field : [
        {
            random:"value 5",
            random2:"second value"
        }
        {
            random:"value 6",
            random2:"second value 6"
        }
        {
            random:"value 7",
            random2:"second value 7"
        }
        {
            random:"value 8",
            random2:"second value 8"
        }
        {
            random:"value 9",
            random2:"second value 9"
        }
    ]
}

i have a collection like this. what i want to do is, when i query this collection, i want only first 2 arrays of the field to return.

expected return:

{
    name : "name 1",
    field : [
        {
            random:"value 1",
            random2:"second value"
        }
        {
            random:"value 2",
            random2:"second value 2"
        }
    ]
}
{
    name : "name 2",
    field : [
        {
            random:"value 5",
            random2:"second value"
        }
        {
            random:"value 6",
            random2:"second value 6"
        }
    ]
}

i've checked Query Modifiers but they are sorting/limiting the documents, not fields in the documents.

So how can i accomplish this?


Solution

  • Use the $slice operator to limit the number of items of an array that a query returns:

    db.collection.find({}, {"name": 1, "field": { "$slice": 2}})