0

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

1 Answer 1

1

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
    }
);
Sign up to request clarification or add additional context in comments.

Comments

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.