How can I query to find mongo entities whose list of sub-entities contain a field matching a string? - mongodb

I have a collection of entities that look like this:
public class ClientEntity {
#Id
private String id;
#Indexed(unique = true)
private String clientId;
private String name;
#DBRef
private List<ClientMachineEntity> machines;
...
}
...where ClientMachineEntity looks like:
public class ClientMachineEntity {
#Id
private String id;
#Indexed(unique = true)
private String clientMachineId;
private String hostName;
...
}
I have a working search that finds ClientEntities by matching against "clientId" and "name":
public List<ClientEntity> searchByIdAndName(String id, String name) {
Criteria idCriteria = Criteria.where("clientId").regex(id, "i");
Criteria nameCriteria = Criteria.where("name").regex(name, "i");
Query query = new Query(new Criteria().orOperator(idCriteria, nameCriteria));
...
}
So my question is, how can I expand this search so that it also matches against "clientMachineId" in the list of sub-entities? I tried adding the following criteria:
Criteria machineCriteria = Criteria.where("machines.clientMachineId").regex(id, "i");
...but that doesn't work, presumably because machines is a LIST of entities, not just a single sub-entity.
UPDATE: It seems like what I'm looking for is the .elemMatch() functionality, but when I try that:
Criteria machineCriteria = Criteria.where("machines").elemMatch(Criteria.where("clientMachineId").regex(id, "i"));
...I get the following error:
org.springframework.data.mapping.model.MappingException: No mapping metadata found for class com.mongodb.BasicDBObject

You can't query by fields in subentities linked with DBRef. If ClientMachineEntity would be embedded in ClientMachine - then you could use dot notation or $elemMatch depending on needs.
In your particular example - couldn't field ClientMachineEntity.clientMachineId be saved as _id and used as a primary key? Then you could get the results you need - take a look at: How to query mongodb with DBRef
My suggestion for development with Spring Data MongoDB is - first learn how to (and if it's possible) do it in plain Javascript with MongoDB console, then learn how to do the same with Spring Data MongoDB.

Related

How to get distinct Items by one field in MongoDB using #Query annotation with pagination enabled

I'm trying to get the list of distinct items by a specific field (userId). Currently I'm using this kind of approach to get records from MongoDB using ReactiveCrudRepository. Additionally, I want this result to be further filtered and get only the distinct items.
How to do this?
#Query(value = "{$and :[{'submitTime':{$ne:null}}, {'gameId': :#{#gameId}} ]}", sort = "{'score': -1, 'timeTaken': 1, 'submitTime': 1}")
Flux<Play> getWinners(#Param("gameId") String gameId, Pageable pageable);
My Play object is like this:
#Document(value = "play")
#Builder
public class Play {
#Id
private String id;
private String gameId;
private int score;
private String userId;
private LocalDateTime submitTime;
private long timeTaken;
}
At the moment #Query annotation doesn't provide a possibility to execute the distinct command.
As a workaround you can
implement a custom method with find, sort and distinct actions
use .distinct() operator after calling your repo method getWinners() to distinct items by key selector, but in this case this operation will not be performed in MongoDB

Spring MongoRepository not returning id field of nested objects [duplicate]

I have a document with an array field with
"chapters": [
{ "id" : "14031871223912313", ...}
...
]
I would like to query return the id's with Spring Data's MongoTemplate using the following:
class Chapter {
private String id;
public String getId() {
return id;
}
}
This way the id is not populated. I have tried using the different mapping options with #Field described here http://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#mapping.conventions.id-field
What am I doing wrong? I know I can always to back to mongo java driver, but I thought this should work.
Thanks in advance for any help.
Found a solution. It is populated via:
#Field("id")
private String chaperId
In MongoDB id's are _id, and every document in mongo has an _id. From the document you linked to, Spring will map #Field String id to mongo's _id field. You probably want to use a #Field('id') String id field mapping to indicate that the field you want is id not _id.

Select nested property from MongoDB repository with Spring Boot

I like the parsing of method names in the MongoRepository so I don't have to write queries. But I was wondering if there is a way to use this pattern to only select a certain (nested) field.
My Document looks like:
#Document(collection = "elements")
public class ElementEntity {
#Id
private String id;
private String type;
private MetaData metaData;
private String json;
}
public class MetaData {
private String title;
private String description;
private final List<String> keywords = new ArrayList<>();
}
I can search ElementEntities by keyword with this:
List<ElementEntity> findByMetaDataKeywords(String keyword);
I now want to get a list of possible keywords, but I don't find any documentation on how or if it is even possible with the method name pattern. I was hoping something like this might work, but it doesn't:
List<String> getDistinctMetaDataKeywordsAsc();
Is there a way to achieve this with just an interface method, or do I need to write a (SQL?) query?
EDIT based on a comment in one of the answers:
Assuming I have two documents in my elements collection:
has the keywords: "disclaimer" and "legal"
has the keywords: "footnote" and "legal"
I want to have a method that returns me a List with the three distinct keywords in alphabetic order: "disclaimer", "footnote", "legal"
try this
List<ElementEntity> findByMetaData_Keywords(List<String> keywords);

Spring Data - Mongo DB - #TextIndexed over #DBRef

Is it possible somehow to search in String fields over #DBRef.
I have this #Document:
public class DocumentFileVersion {
#TextIndexed
#DBRef
private OtherObject otherObject
and I will search in String fields of otherObject. Is there any possibility to do that?
DBRef are designed to be queried by id reference only.
So it is not possible. You should rethink your schema structure.

search by param values of referenced objects in mongodb

Is it possible to search based on some param value of a DBRef object in spring data.
eg. say we have two objects, Car, and Company as shown
Class Car {
#Id
String id;
String model;
#DBRef
Company company;
}
Class Company {
#Id
String id;
String name;
}
Can I write a query to fetch all car's of Hyundai company like this,
Query queryForCars = new Query(Criteria.where("company.name").is("Hyundai")), Car.class)
It works fine for non referenced objects, but for referenced object it's working in my case.
Thanks for your help.
For referenced objects this is how your query should look like:
Query queryForCars = new
Query(Criteria.where("company.$name").is("Hyundai")), Car.class)