[SERVER-53743] mongodb $slice aggregate operator issue when third argument is 0 { $slice: [ <array>, <position>, <n> ] } Created: 06/Dec/20  Updated: 27/Oct/23  Resolved: 15/Jan/21

Status: Closed
Project: Core Server
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: John Anto Assignee: Edwin Zhou
Resolution: Works as Designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Participants:

 Description   

Problem Description

Consider the below Mongodb Query.
 

{{  db.groups.aggregate([{        $match: {        _id: {            $in: [220]
        },        active: true        }
    },
    {        $project: {        myArr: {            $slice: ["$arr", -1, 0]
        },        name: 1                }
    }]).pretty()}}

When I execute this query I encounter error:
 

{{2020-12-05T19:16:43.002-0500 E  QUERY    [js] uncaught exception: Error: command failed: {    "operationTime" : Timestamp(1607213793, 1),    "ok" : 0,    "errmsg" : "Third argument to $slice must be positive: 0",    "code" : 28729,    "codeName" : "Location28729",    "$clusterTime" : {        "clusterTime" : Timestamp(1607213793, 1),        "signature" : {            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),            "keyId" : NumberLong(0)
        }
    }
} : aggregate failed :}}

As per the $slice documentation, https://docs.mongodb.com/manual/reference/operator/aggregation/slice/ the third argument ('n') to the $slice aggregate operator cannot be negative if the second argument 'position' is specified. I calculate the third argument value to 0 which means, I expect 0 array elements as the result. However, I encounter errmsg" : "Third argument to $slice must be positive: 0".

Please suggest if my understanding is incorrect as the query doesn't execute as I expect.

Steps to Reproduce

 
{{  db.groups.aggregate([{        $match: {        _id: {            $in: [220]
        },        active: true        }
    },
    {        $project: {        myArr: {            $slice: ["$arr", -1, 0]
        },        name: 1                }
    }]).pretty()}}

Expected Results

Expecting myArr should be empty array.

Actual Results

"errmsg" : "Third argument to $slice must be positive: 0",

Additional Notes



 Comments   
Comment by Edwin Zhou [ 15/Jan/21 ]

Hi javatutorials2016@gmail.com,

If <position> is specified, <n> must resolve to a positive integer.. Since 0 is non-positive, we should expect an error indicating that the value must be positive.

Best,
Edwin

Generated at Thu Feb 08 05:31:45 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.