How to get MongoDB object by MongoTemplate without model class

Viewed 2497

I am trying to get a Mongo collection object. I don't want to use model because my fields are not fixed in Mongo collection.

Here my customer_ref and _id are fixed fields, and other fields are not. It might be that fields are added or removed.

How can I access $ref and $id fields which are references of other collections?

{
  "_id" : "SQ74P",
  "_class" : "com.vo.License",
  "vendor" : "te",
  "product" : "ty",
  "product_id" : "7.4",
  "version" : "17.0",
  "is_deleted" : false,
  "customer_ref" : {
    "$ref" : "customer",
    "$id" : "IG_7.4"
  }
}

I have tried this:

Controller:

@RestController
@EnableAutoConfiguration
@RequestMapping("/license/demo")
public class DemoLiController {

  @Autowired
  DemoLicRepository demoLicRepository;

  @RequestMapping(value = "/lic", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<Map<String, Object>> findLicense() throws Exception {
    Map<String, Object> test = demoLicRepository.findbylic("SIT1");
    return  new ResponseEntity<Map<String, Object>>(test, HttpStatus.OK);
  }

Repository:

@Repository
public class DemoLicRepository {

  @Autowired
  MongoTemplate template;

  public Map<String, Object> findbylicenseid(String key) throws Exception {
    Query findQuery = new Query();
    findQuery.addCriteria(Criteria.where("_id").is(key));
    template.findOne(findQuery, Map.class, "win_lic");
    Map<String, Object> res = template.findOne(findQuery, Map.class, "win_licenses_poc");
    return template.findOne(findQuery, Map.class, "win_licenses_poc")
}

If I remove the customer_ref block the code is working fine.

0 Answers
Related