mongodbspring-boot

How to use Wildcard in mongoDB using Spring boot?


I'm trying to run a simple search query but it's returning me an empty array, there are about three records are in the databse. I have other queries too they all working fine. Can anyone point me to the right direction please.

Model

@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "order")
public class OrderDTO {
    
    @Id
    private String ordId;
    private List<Category> categoryName;
}

Repository

@Repository
public interface OrderRepository extends MongoRepository<OrderDTO, String> {

    @Query("{'categoryName': {'$regex': ?0 }})")
    public List<OrderDTO> findByCategoryName(String categoryName);
}

Service

public List<OrderDTO> searchOrderByCategoryName(String categoryName){
    return or.findByCategoryName(categoryName);
    }
    

Controller

@RestController
@RequestMapping("/portal")
@CrossOrigin(origins = "http://localhost:3000")
public class OrderController {

    @Autowired OrderService os;
    
    @GetMapping("/search/{categoryName}")
    public List<OrderDTO> searchOrderByCategoryName(@PathVariable(value = "categoryName") String categoryName) {
    return os.searchOrderByCategoryName(categoryName);
}

Database

    {
  "_id": {
    "$oid": "678ed41ceac5b05ec1a2dea8"
  },
  "categoryName": [
    {
      "categoryName": "N"
    }
  ],
  "productName": [
    {
      "productName": "9999999"
    },
    {
      "productName": "888888"
    },
    {
      "productName": "77777777"
    },
    {
      "productName": "55555555"
    }
  ],
  "productQuantity": 90,
  "ordUpdated": {
    "$date": "2025-01-20T22:54:20.729Z"
  },
  "isInStock": false,
  "_class": "com.softoffice.portal.model.OrderDTO"
}

Solution

  • Since you're querying for an object property in an array of objects, you actually need to query for categoryName.categoryName:

    @Repository
    public interface OrderRepository extends MongoRepository<OrderDTO, String> {
        @Query("{'categoryName.categoryName': {'$regex': ?0 }}")
        public List<OrderDTO> findByCategoryName(String categoryName);
    }