skip to Main Content

How can I find only the "hotels" property? Data in MongoDB-

[
    {
        "picture": "https://d.bcb.ic/dKkqr2da/lalkhal.jpg",
        "name": "Lalakhal",
        "about": "Lalakhal is....",
        "latitude": 25.1048,
        "longitude": 92.1770,
        "hotels": [{}, {}, {}]
    },
    {
        "picture": "https://d.bcb.ic/dKkqr2da/lalkhal.jpg",
        "name": "Lalakhal",
        "about": "Lalakhal is....",
        "latitude": 25.1048,
        "longitude": 92.1770,
        "hotels": [{}, {}, {}]
    },
]

Here is my code

const places = client.db("travel-guru").collection("places");
const hotels = await places.findOne({name: placename})

I don’t need the all result document. I need just hotels only for a specific document. I am expecting the result-
hotels = [{}, {}, {}]

3

Answers


  1. you can refer to this projection document MongoDB projection

    const hotels = await places.findOne({name: placename},{hotels: 1})
    

    if you don’t want id also then

    const hotels = await places.findOne({name: placename},{hotels: 1, _id:0})
    

    Here 1 means that you want that field in the response and 0 means you want to avoid that field in response

    Login or Signup to reply.
  2. await places.findOne({name: placename}).project({hotels: 1, _id: 0})

    Login or Signup to reply.
  3. You can simply use the select property to show only required fields.If you want to include _id then you remove _id property from select else it is added in projection by default.

    const hotels = await places.findOne({name: placename}).select({hotels:1,_id:0});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search