Home > OS >  Load/Read Array of object in MongoDB
Load/Read Array of object in MongoDB

Time:11-10

suppose I have some data in MongoDB like -

    [
      {
        _id: new ObjectId("63608e3c3b74ed27b5bdf6fa"),
        latitude: 24.3065,
        hotels: [
          {
            name: "Saunders Oconnor",
            latitude: 22.05869172633478,
            longitude: 88.661309245504,
          },
          {
            name: "Saunders Oconnor",
            latitude: 22.05869172633478,
            longitude: 88.661309245504,
          },
        ],
      },
      {
        _id: new ObjectId("63608e3c3b74ed27b5bdf6fa"),
        latitude: 24.3065,
        hotels: [
          {
            name: "Saunders Oconnor",
            latitude: 22.05869172633478,
            longitude: 88.661309245504,
          },
          {
            name: "Saunders Oconnor",
            latitude: 22.05869172633478,
            longitude: 88.661309245504,
          },
        ],
      }
    ];

How can I read only a field that match my hotel name.

I am trying this-

const hotel = await places.find({ name: placeName }).project({ hotels: 1 }).toArray();

It returns me an array. like -

[
  {
    _id: new ObjectId("63608e3c3b74ed27b5bdf6f8"),
    hotels: [ [Object], [Object], [Object], [Object], [Object] ]
  }
]

But I don't want this. How can I read only a field that matches the hotel name? like -

{
 name: "Saunders Oconnor",
 latitude: 22.05869172633478,
 longitude: 88.661309245504,
}

CodePudding user response:

If I've understood correctly you can use this aggregation pipeline:

  • First step is to deconstruct the array and can use values as object.
  • Then $match to get only hotels you want.
  • And the last step is to project the values you want.
db.collection.aggregate([
  {
    "$unwind": "$hotels"
  },
  {
    "$match": {
      "hotels.name": "Saunders Oconnor"
    }
  },
  {
    "$project": {
      "name": "$hotels.name",
      "latitude": "$hotels.latitude",
      "longitude": "$hotels.longitude"
    }
  }
])

Example here

  • Related