Home > Blockchain >  How can I filter records with multiple $in condition (some are optional $in) with arrays of string?
How can I filter records with multiple $in condition (some are optional $in) with arrays of string?

Time:10-16

You can see my Mongodb Records at last... I am now trying to implement search functionality, I mad checkbox filtration for my project and below I listed those arrays after I clicked multiple checkboxes (see 1, 2 and 3).

I tried in aggregate with multiple match queries with $in, but it doesn't worked. Below arrays are used to check the records.

for example: ["Restaurant", "Mall"] need to check with "commercialType" in records, at the same time ["AC Rooms", "3 Phase Electricity"] need to check with "propertyFeatures.name" in records.. so all matching records must display if records exist with those filtrations.

I tried with multiple $in queries like this, but it gives empty records.

"$match": {
  "commercialType": {
    "$in": ["Restaurant", "Hotel"]
 },
 {
  "propertyFeatures.name": {
    "$in": ['AC Rooms']
  }
 },
 ... other match filters
}

1. Below Array is used to find commercialType (field in doc)
[
            'Restaurant',
            'Office space',
            'Hotel'
]
2. Below Array is used to find landType (field in doc)
[
            'Bare land',
            'Beachfront land',
            'Coconut land'
 ]
3. Below Array is used to find "propertyFeatures.name" (field in doc)
        [
            'AC Rooms',
            '3 Phase Electricity',
            'Hot Water'
        ]
[
  {
    "_id": {
      "$oid": "6343b68edf5e889a575c8502"
    },
    "propertyType": "House",
    "propertyFeatures": [
      {
        "id": 1,
        "name": "AC Rooms",
        "value": true
      }
    ]
  },
  {
    "_id": {
      "$oid": "6343b68edf5e889a575c8502"
    },
    "propertyType": "Land",
    "landType": "Bare land",
    "propertyFeatures": [
      {
        "id": 1,
        "name": "Wider Road",
        "value": true
      }
    ]
  },
  {
    "_id": {
      "$oid": "6343b68edf5e889a575c8502"
    },
    "propertyType": "Commercial",
    "commercialType": "Restaurant",
    "propertyFeatures": [
      {
        "id": 1,
        "name": "3 Phase Electricity",
        "value": true
      }
    ]
  }
]

CodePudding user response:

You are probably missing $or operator, so your example pipeline becomes

[
  {"$match": {
    "$or": [
      {
        "commercialType": {
          "$in": ["Restaurant", "Hotel"]
       },
       {
        "propertyFeatures.name": {
          "$in": ['AC Rooms']
        }
      } 
    ]
  }
]

MongoDB docs: https://www.mongodb.com/docs/manual/reference/operator/aggregation/or/#error-handling

  • Related