问题
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