0

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

1 Answer 1

1

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

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.