manny
manny

Reputation: 415

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?

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

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 ]
}

Upvotes: 0

Views: 27

Answers (1)

Dheemanth Bhat
Dheemanth Bhat

Reputation: 4452

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
    }
);

Upvotes: 1

Related Questions