[英]How to query and fetch one item that is in an array from mongodb?
I'm new to MongoDB/Mongoose and I am using MongoDB, Node and Express how to query and fetch one item that is in an array from mongodb?我是 MongoDB/Mongoose 的新手,我正在使用 MongoDB、Node 和 Express 如何从 mongodb 查询和获取数组中的一项?
Here is the database structure这是数据库结构
{
"_id" : ObjectId("5e19d76fa45abb5d4d50c1d3"),
"name" : "Leonel Messi",
"country" : "Argentina",
"awards" : [ "Ballon d'Or", "Golden Boot", "FIFA World Player of the Year",]
}
Here is the query using mongoose and express in node js environment这是使用 mongoose 并在 node js 环境中表达的查询
router.get('/FindPlayers', async (req, res) => {
const player = await Players.findOne({ name: "Leonel Messi" }, { country: 1, awards: [0], _id: 0, });
res.send(player);
});
I would like to get the county and the first item in the awards array only like this below我只想像下面这样获得县和奖项数组中的第一项
{
country : "Argentina",
awards : [ "Ballon d'Or" ]
}
But instead I am getting但相反,我得到
{
country : "Argentina",
awards : [ 0 ]
}
try this:尝试这个:
const player = await Players.findOne(
{
name: "Leonel Messi"
},
{
country: 1,
awards: { $arrayElemAt: ["$awards", 0] },
_id: 0
}
);
// or
const player = await Players.findOne(
{
name: "Leonel Messi"
},
{
country: 1,
awards: { $first: "$awards" },
_id: 0
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.