admin管理员组

文章数量:1410712

I'm building a ride-sharing platform where rides have multiple stops stored as an array of objects in MongoDB. Each stop contains a cityName field (e.g., "Lahore Pakistan").

Users search for rides by providing pickup and drop city names, but the issue is that city names in the database may have variations (e.g., "Lahore Pakistan" instead of "Lahore").

I need a MongoDB aggregation query that:

  • Matches rides where both pickup and drop exist in the stops array
  • Uses regex for flexible city name matching
  • Ensures case-insensitive search
  • Returns ride details along with driver and vehicle info

Example Stops Data:

{
    "stops": [
        { "cityName": "Lahore  Pakistan" },
        { "cityName": "Multan  Pakistan" },
        { "cityName": "Karachi  Pakistan" }
    ]
}

If a user searches for:
pickup=Mardan&drop=Lahore, it should return the ride if both cities exist in the ride's stops.

My Attempted Query (Not Working as Expected):

const pickupRegex = new RegExp(`^${pickup}`, "i");
const dropRegex = new RegExp(`^${drop}`, "i");

const rides = await Ride.aggregate([
    {
        $match: {
            stops: {
                $elemMatch: { cityName: pickupRegex }, // Match pickup city
                $elemMatch: { cityName: dropRegex }    // Match drop city
            }
        }
    }
]);

The query does not return results as expected. I've tried multiple approaches, but it seems $elemMatch does not work for matching two different elements in the same array.

How can I correctly filter rides where both pickup and drop locations exist in the stops array using MongoDB aggregation with regex?

I'm building a ride-sharing platform where rides have multiple stops stored as an array of objects in MongoDB. Each stop contains a cityName field (e.g., "Lahore Pakistan").

Users search for rides by providing pickup and drop city names, but the issue is that city names in the database may have variations (e.g., "Lahore Pakistan" instead of "Lahore").

I need a MongoDB aggregation query that:

  • Matches rides where both pickup and drop exist in the stops array
  • Uses regex for flexible city name matching
  • Ensures case-insensitive search
  • Returns ride details along with driver and vehicle info

Example Stops Data:

{
    "stops": [
        { "cityName": "Lahore  Pakistan" },
        { "cityName": "Multan  Pakistan" },
        { "cityName": "Karachi  Pakistan" }
    ]
}

If a user searches for:
pickup=Mardan&drop=Lahore, it should return the ride if both cities exist in the ride's stops.

My Attempted Query (Not Working as Expected):

const pickupRegex = new RegExp(`^${pickup}`, "i");
const dropRegex = new RegExp(`^${drop}`, "i");

const rides = await Ride.aggregate([
    {
        $match: {
            stops: {
                $elemMatch: { cityName: pickupRegex }, // Match pickup city
                $elemMatch: { cityName: dropRegex }    // Match drop city
            }
        }
    }
]);

The query does not return results as expected. I've tried multiple approaches, but it seems $elemMatch does not work for matching two different elements in the same array.

How can I correctly filter rides where both pickup and drop locations exist in the stops array using MongoDB aggregation with regex?

Share Improve this question edited Mar 10 at 15:24 jonrsharpe 122k30 gold badges268 silver badges476 bronze badges asked Mar 10 at 14:39 Muhammad SohaibMuhammad Sohaib 1
Add a comment  | 

1 Answer 1

Reset to default 1

1. Your stops object is clearly repeating $elemMatch as a key/property, which is either not allowed or one will override the other.

2. You don't need to use $elemMatch here because you're only checking the value of one property, and not multiple properties of the same object. And you're expecting different cities to match the pickup and drop so it will be different elements in the array.

3. Use $match with $and for the two conditions:

Ride.aggregate([
  {
    $match: {
      $and: [
        { "stops.cityName": pickupRegex }, // Match pickup city
        { "stops.cityName": dropRegex }    // Match drop city
      ]
    }
  }
])

Mongo Playground

本文标签: mongodbSearch Rides by City Name in Stops Array Using RegexStack Overflow