Sean
Sean

Reputation: 1364

Mongoose - Search an array and return the matched results

I am looking for a way to return matched items under an array in Mongo (mongoose).

The data structure is like this:

[
  {
    "_id": {
      "$oid": "123456"
    },
    "make": "Lamborghini",
    "makeLogo": "/images/makeLogos/lamborghini.png",
    "models": [
      {
        "model": "Aventador",
        "_id": {
          "$oid": "678909t"
        }
      },
      {
        "model": "Countach",
        "_id": {
          "$oid": "678909"
        }
      }
    ],
    "__v": 0
  },
  {
    "_id": {
      "$oid": "2345678i90"
    },
    "make": "Nissan",
    "makeLogo": "/images/makeLogos/nissan.png",
    "models": [
      {
        "model": "350z",
        "_id": {
          "$oid": "678909gggg"
        }
      },
      {
        "model": "370z",
        "_id": {
          "$oid": "678909rrrrr"
        }
      }
    ],
    "__v": 0
  }
]

I would like to search: 3 and it should return 350z and 370z to me.

I tried the below:

modelsModel.find(
    {"models.model": { $regex: req.query.carModel + '.*', $options:'i'}},
)
.exec(function(err, models) {
    if(err){
        res.status(400).json({error: err});
    } else {
        res.status(200).json({cars: models});
    }
});

Where the data returned is this:

[ 
  { _id: 5ca893b7587ab519613b806e,
    make: 'Lamborghini',
    makeLogo: '/images/makeLogos/lamborghini.png',
    __v: 0,
    models: [ 
      [Object], [Object]
    ] 
  } 
]

This is when I searched for Countach which has a match.

I know I am doing something very obviously wrong here but this is so new to me I don't even know where to begin.

Thanks in advance!

Upvotes: 1

Views: 50

Answers (1)

Ashh
Ashh

Reputation: 46491

You can use below aggregation with mongodb 4.2

db.collection.aggregate([
  { "$match": {
    "models.model": { "$regex": "A" }
  }},
  { "$project": {
    "models": {
      "$filter": {
        "input": "$models",
        "cond": {
          "$regexMatch": {
            "input": "$$this.model",
            "regex": "A"
          }
        }
      }
    }
  }}
])

Upvotes: 1

Related Questions