How to get parent object based upon key from child map in MongoRepository JAVA SpringBoot

我怕爱的太早我们不能终老 提交于 2020-02-06 07:54:28

问题


This is how my object looks.

@Document("parent")
public class Parent {
    @Id 
    private String id;
    private String field-1;
    private Map<String,Long> someMap;
}


{
    "_id" : "parent-id",
    "field-1" : "some value",
    "someMap" : {
        "category-5" : 123,
        "category-4" : 456
    }
}

I want to get this entire object when i search with "category-5" or "category-4". I am using MongoRepository and SpringBoot.

I tried following approach but its not working for me

public interface ParentRepo extends MongoRepository<Parent, String> {

    @Query("{someMap :{$in: [?0]}}")
    List<Parent> findBySomeMap(String id);
}



or if anyone can help me to convert this into MongoRepository/@Query method that would be great and much appreciated Goal here is to pass CategoryId as a parameter to query

db.getCollection('parentCollection').find({"someMap.category-4" : {$exists:true}})

This method returns expected results


回答1:


package com.somepackage.services;

import org.springframework.stereotype.Service;
import java.util.List;
import com.yourpackagestructure.Parent;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

@Service
public class Service{

   private MongoTemplate mongoTemplate;

   public Service(MongoTemplate mongoTemplate){
    this.mongoTemplate = mongoTemplate;
   }

   public List<Parent> getParentList(String mapKey){
    Query query = new Query();
    query.addCriteria(Criteria.where("someMap." + mapKey).exists(true));
    List<Parent> parents = mongoTemplate.find(query,Parent.class);
   }
}


来源:https://stackoverflow.com/questions/59824067/how-to-get-parent-object-based-upon-key-from-child-map-in-mongorepository-java-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!