Skip to content

Slice only one element from an array in MongoDB

Advertisements

Let’s say we have two documents in a MongoDB collection called scores and I would like to fetch the latest score of Ron. I need to fetch the latest element from an array of scores and we can use $slice for this purpose.

[
  {
    "_id": {
      "$oid": "5e16e8a3c3775d62f3acbe6e"
    },
    "name": "Naveen",
    "score": [
      9,
      8,
      18,
      76,
      65,
      4,
      0,
      8
    ]
  },
  {
    "_id": {
      "$oid": "5e16e8a3c3775d62f3acbe71"
    },
    "name": "Ron",
    "score": [
      19,
      82,
      8,
      6,
      45,
      45,
      99,
      8
    ]
  }
]

To fetch the latest score of Ron, we can query the collection like this.

Advertisements
db.scores.findOne({name: "Ron"},{score : {$slice : 1} ,"name":0,"_id":0})
{"score":[19]}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.