ddriver1
ddriver1

Reputation: 733

Getting first element of embedded array in mongoDB using Node JS driver

Let's say I have the following document stored in a mongoDB collection 'people':

{ 
      _id: 489324,
     name: "Ryan Jones"
   skills: [ "fishing", "programming" ]
}

I am trying to retrieve Ryan Jones's first skill in the array (skills[0]).

This seems like a dead simple operation but I can't seem to do it using the Node JS driver. I can retrieve just the skills array easily:

db.collection('people').findOne({ name:"Ryan Jones"},{ projection: { skills:1 }})

...but I don't want to transfer the whole array over the wire. I just want to get "fishing".

I have tried using slice and arrayElemAt within projection but I get a MongoError. How can I achieve this using the NodeJS driver? Does it require a more complex aggregation operation instead of findOne?

Upvotes: 1

Views: 613

Answers (2)

Valijon
Valijon

Reputation: 13113

Try this one:

db.collection('people').findOne({
  name: "Ryan Jones"
},
{
  skills: {
    $slice: 1
  }
})

MongoTemplate with .find

Upvotes: 1

Shubham Dixit
Shubham Dixit

Reputation: 1

You can achieve that with aggregation , with $arrayElemAt something like this

db.collection('people').aggregate([
  {
    $match: {
      name: "Ryan Jones"
    }
  },
  {
    $project: {
      name: 1,
      skills: {
        $arrayElemAt: [
          "$skills",
          0
        ]
      },

    }
  }
])

See demo here

Upvotes: 1

Related Questions