Mongo $ slice reverse index request out of range

The following query in mongo behaves strangely:

db.items.findOne({},{ "List": { "$slice": [ skip, 3 ] }})

First: Instead of returning a single object with just ["_id", "List"], it returns the full object.

Secondly: if skipnegative, but |skip|higher than list.length, then it returns the first three elements, as ifskip==0

I would expect:

{
       "_id" : ObjectId("542babf265f5de9a0d5c2928"),
       "List" : [
                1,
                2,
                3,
                4,
                5
        ]
        "other" : "not_important"
}

inquiry:

db.items.findOne({},{ "List": { "$slice": [-10, 3 ] }})

To obtain:

{
       "_id" : ObjectId("542babf265f5de9a0d5c2928"),
       "List" : []
}

instead, I get:

{
       "_id" : ObjectId("542babf265f5de9a0d5c2928"),
       "List" : [
                1,
                2,
                3
        ]
        "other" : "not_important"
}

Why?

I am using mongoDB 2.4.10

+4
source share
2 answers

Second: if the skip is negative and | skip | higher than list.length then it returns the first three elements as if skip == 0

. javascript Array.prototype.slice(), mongodb.

ECMAScriptยฎ Language Specification,

relativeStart , k - max ((len + relativeStart), 0); else k - min (relativeStart, len).

relativeStart is -10, k = max((-10+5),0), k = 0; (, 5 - ).

, k skip 0, .

: , [ "_id", "List" ], .

, . inclusion exclusion, , $slice, $elemmatch.

db.items.findOne({},{"_id":1,"List": { "$slice": [-10, 3 ] }})

:

{ "_id" : ObjectId("542babf265f5de9a0d5c2928"), "List" : [ 1, 2, 3 ] }

findOne() - not only for simple projection, , field 0 1 > . . - projection operator, applied projected.

, -, , $slice.

  • .
  • , , $slice, , , .

, .

  • , , .
  • , '0' '1': "0" - , . "1", , .
  • .
+4

$slice, , MongoDB 3.2 $slice:

:

{ "_id" : ObjectId("5922846dbcf60428d0f69f6e"), "a" : [ 1, 2, 3, 4 ] }
{ "_id" : ObjectId("5922847cbcf60428d0f69f6f"), "a" : [ 5, 6 ] }

$size $slice, , :

db.collection.aggregate([
  { "$project": {
    "a": {
      "$cond": {
        "if": { "$gte": [ { "$size": "$a" }, 4 ] },
        "then": { "$slice": [ "$a", -4, 2 ] },
        "else": { "$literal": [] },
      }
    }
  }}
])

, , :

{ "_id" : ObjectId("5922846dbcf60428d0f69f6e"), "a" : [ 1, 2 ] }
{ "_id" : ObjectId("5922847cbcf60428d0f69f6f"), "a" : [ ] }

, MongoDB "", .

+1

All Articles