cannot use $slice in nested array

Viewed 29

what i try is to $slice an array inside an array.

This is what i tried but it fails.

db.collection.find({
  name: "admin",
  "datasets.name": "test"
},
{
  "datasets.$.datapoints": {
    $slice: [
      0,
      3
    ]
  }
})

Example input data

[
  {
    "name": "admin",
    "datasets": [
      {
        "name": "test",
        "datapoints": [
          1,
          6,
          4,
          3,
          8,
          5,
          3
        ],
        "_id": {
          "$oid": "619288f16733758444a28728"
        }
      },
      {
        "name": "more datasets",
        "datapoints": [
          1,
          2,
          3,
          4,
          5,
          6,
          7,
          8
        ],
        "_id": {
          "$oid": "619289086733758444a2872a"
        }
      }
    ]
  }
]

Playground link:

https://mongoplayground.net/p/pmGpk9jtqZ2

Output should be:

{ name: "test", datapoints: [1,6,4] }
1 Answers

You can get the results you want

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "datasets": [
      {
        "_id": ObjectId("619288f16733758444a28728"),
        "datapoints": [
          1,
          6,
          4
        ],
        "name": "test"
      },
      {
        "_id": ObjectId("619289086733758444a2872a"),
        "datapoints": [
          1,
          2,
          3
        ],
        "name": "more datasets"
      }
    ],
    "name": "admin"
  }
]

with

db.collection.find({
  name: "admin",
  "datasets.name": "test"
},
{
  "datasets.datapoints": {
    $slice: [
      0,
      3
    ]
  }
})

You just had to omit the positional operator.

Related