This is a document I want to search. Collection is CustmObjects
. This is one CustomObject
{
"id" : "id_1",
"name" : "name_1";
"additionalData" : [
{
"additionalDataId" : "id_1_1",
"additionalDataName" : "name_1_1",
"longText" : "A long story about..."
},
{
"additionalDataId" : "id_1_2",
"additionalDataName" : "name_1_2",
"longText" : "A longer story about danger..."
},
{
"additionalDataId" : "id_1_3",
"additionalDataName" : "name_1_3",
"longText" : "A longer story about danger and courage"
},
]
}
To retrieve a document with name name_1 is easy.
final nameToSearchBy = "name_1";
Query query = new Query();
Criteria criteria = Criteria.where("name").is(nameToSearchBy);
query.addCriteria(criteria);
mongoTemplate.findOne(query, CustomObject.class, "CUSTOM_OBJECTS_COLLECTION");
Now my question. How to retrieve additionalData
with name "id_1_2"
? I do not need to retrieve the whole document, only an entry in the array.
Of course, I can retrive a whole document and iterate through its additionalData
values in java program. But I want to delegate this job to database server.
I tried
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(Criteria.where("name").is("name_1").and("additionalData.additionalDataName").is("name_1_2")),
Aggregation.project("additionalData"),
);
mongoTemplate.aggregate(aggregation, "CustmObjects", Object.class);
It returns all elements of the array. I need only one matching element.
Update
This is what I want to do Retrieve only the queried element in an object array in MongoDB collection
db.find({shapes: {"$elemMatch": {name: "name_1_2"}}}, ... )
As I understand, what the second part is projection to select fields. I need all the fields from array element.
{"shapes.color": 1}
The second link Spring data Match and Filter Nested Array
The result I want to get is this
{
"additionalDataId" : "id_1_2",
"additionalDataName" : "name_1_2",
"longText" : "A long story about..."
}
is more comlex, it has array inside of element which is inside of array. Please, I need something more simple and working.