1

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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this aggregation also works and after timing operations vs the findOne method Valijon proposed there is no difference in speed.
1

Try this one:

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

MongoTemplate with .find

1 Comment

I managed to get this to work by wrapping it in { projection : ... } which is needed for the NodeJS driver. However, the default behaviour is to then project the other fields in the document so I had to manually set them to not project, i.e._id:0, name:0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.