0

I am using Mongoose and Express to create an API and need your help to find a specific document inside the hotels array. I need to find the document with an id matching a specific value.

Here is the schema:

{
  "_id": "5e181fed9fc1883a69797e3a",
  "hotels": [
    {
      "name": "Hotel Emperador",
      "stars": 4,
      "price": 1596,
      "imagen": "https://i.ibb.co/RHYqxjL/hotel1.jpg",
      "id": 1
    },
    {
      "name": "Hotel Sonesta",
      "starts": 4,
      "price": 2400,
      "imagen": "https://i.ibb.co/kx06vbZ/hotel2.jpg",
      "id": "sonesta"
    },
    {
      "name": "Hotel Soratama",
      "stars": 3,
      "price": 1000,
      "imagen": "https://i.ibb.co/hx0Txk6/hotel3.jpg",
      "id": "3"
    }
  ]
}

I need something like this response, for the get_id in my api, but I cannot do it, can you help me?

{
  "name" : "Hotel Emperador",
  "stars" : 4,
  "price" : 1596,
  "imagen" : "https://i.ibb.co/RHYqxjL/hotel1.jpg",
  "id": 1
}
0

1 Answer 1

0

You can use the aggregation framework to retrieve the document

hotelModel.aggregate([{
    $match:{
        _id: "5e181fed9fc1883a69797e3a"
    }
},{ $project: {
          hotels: { $filter: {
              input: '$hotels',
              as: 'hotel',
              cond: { $eq: ['$$hotel.id', 1]}
          }},
          _id: 0
      }

},{
   $unwind:"$hotels" 
}])

https://mongoplayground.net/p/ka5WAdCvuZG

references:

https://docs.mongodb.com/manual/reference/operator/aggregation/filter/ https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.