0

We need to accomplish the nearest search based on document properties in MongoDB.

Let's take an example, there is a Car schema in MongoDB, information will be stored as something similar to:

{
  Make: "Hyundai",
  Model: "Creta",
  Title: "Hyundai Creta E 1.6 Petrol",
  Description: "Compact SUV",
  Feature: {
    ABS:    true,
    EBD:    true,
    Speakers: 4,
    Display: false
  },
  Specification: {
    Length: "4270 mm",
    Width: "1780 mm",
    Height: "1630 mm",
    Wheelbase:  "2590 mm",
    Doors:  5,
    Seating:    5,
    Displacement: "1591 cc"
  },
  Safety: {
    Airbags: 2,
    SeatBeltWarning: false
  },
  Maintenance: {
    LastService: "21/06/2016",
    WashingDone: true
  }
}

Search needs to be provided based on following criteria:

1. Make
2. Model
3. ABS
4. Seating
5. Displacement
6. Airbags

Now results should contain records where 3 or more of the properties match (exact match), and ordered based on the maximum number of properties that match.

What is the best way to implement this with MongoDB?

Frits
  • 7,341
  • 10
  • 42
  • 60
Gaurav Arya
  • 211
  • 3
  • 7

1 Answers1

0

You could write something to generate documents for each triplet of fields, and then put them together with $or, producing something like

{$or: [
    {Make: "Hyundai", Model: "Creta", Feature.ABS: true},
    {Make: "Hyundai", Model: "Creta", Specification.Seating: 5},
    ...
]}

Sorting probably requires sorting by textScore.

Alex
  • 780
  • 4
  • 12