Home > Mobile >  Why is this error occurring: MongoServerError: unknown operator: $slice
Why is this error occurring: MongoServerError: unknown operator: $slice

Time:11-02

Given the following JSON in the articles collection:

[
  {
    _id: 1,
    description: 'DESCRIPTION ARTICLE AB',
    article_code: 'AB',
    purchase: [
      { company: 1, cost: Decimal128("80.010000") },
      { company: 2, cost: Decimal128("85.820000") },
      { company: 3, cost: Decimal128("79.910000") }
    ],
    stock: [
      { country: '01', warehouse: { code: '02', units: 10 } },
      { country: '02', warehouse: { code: '02', units: 8 } }
    ]
  },
  {
    _id: 2,
    description: 'DESCRIPTION ARTICLE AC',
    article_code: 'AC',
    purchase: [
      { company: 1, cost: Decimal128("90.010000") },
      { company: 2, cost: Decimal128("95.820000") },
      { company: 3, cost: Decimal128("89.910000") }
    ],
    stock: [
      { country: '01', warehouse: { code: '01', units: 20 } },
      { country: '02', warehouse: { code: '02', units: 28 } }
    ]
  }
]

I'm trying to get the right syntax for $slice, but this command:

db.articles.find({"stock.country": '01', "stock": {$slice: 1}})

produces this error message:

MongoServerError: unknown operator: $slice

What is the right syntax to use $slice to get only the first element of the stock array?

CodePudding user response:

$slice is a projection operator ( or an aggregate expressions but in this case we're not using the aggregation pipeline ).

This means you need to use it in the projection portion, not the query portion of the command.

db.collection.find(
   <query>,
   { <arrayField>: { $slice: <number> } }
);

Or specifically for you:

db.collection.find({
  "stock.country": "01"
},
{
  stock: {
    $slice: 1
  }
})

Mongo Playground

  • Related