Home > other >  Load a single data from a document in mongoDB
Load a single data from a document in mongoDB

Time:11-02

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 = [{}, {}, {}]

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

  • Related