Reputation: 733
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
Reputation: 13113
Try this one:
db.collection('people').findOne({
name: "Ryan Jones"
},
{
skills: {
$slice: 1
}
})
Upvotes: 1
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