使用 Node JS 驱动程序在 mongoDB 中获取嵌入式数组的第一个元素 [英] Getting first element of embedded array in mongoDB using Node JS driver
问题描述
假设我将以下文档存储在 mongoDB 集合people"中:
Let's say I have the following document stored in a mongoDB collection 'people':
{
_id: 489324,
name: "Ryan Jones"
skills: [ "fishing", "programming" ]
}
我正在尝试检索 Ryan Jones 在数组中的第一个技能 (skills[0]).
I am trying to retrieve Ryan Jones's first skill in the array (skills[0]).
这似乎是一个非常简单的操作,但我似乎无法使用 Node JS 驱动程序来完成.我可以轻松检索技能数组:
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".
我曾尝试在投影中使用 slice 和 arrayElemAt,但出现了 MongoError.如何使用 NodeJS 驱动程序实现此目的?它是否需要更复杂的聚合操作而不是 findOne?
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?
推荐答案
试试这个:
db.collection('people').findOne({
name: "Ryan Jones"
},
{
skills: {
$slice: 1
}
})
这篇关于使用 Node JS 驱动程序在 mongoDB 中获取嵌入式数组的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!