I have a below mongo document stored
{
"Field1": "ABC",
"Field2": [
{ "Field3": "ABC1","Field4": [ {"id": "123" }, { "id" : "234" }, { "id":"345" }] },
{ "Field3": "ABC2","Field4": [ {"id": "123" }, { "id" : "234" }, { "id":"345" }] },
{ "Field3": "ABC3","Field4": [{ "id":"345" }] },
]
}
from the above, I want to fetch the subdocuments which is having id "123"
ie.
{
"Field3" : "ABC1",
"Field4" : [ { "id": "123"} ]
} ,
{
"Field3" : "ABC2",
"Field4" : [ { "id": "123"} ]
}
1. Java way A. use Mongo find method to get the ABC document from Mongo DB B. for Loop to Iterate the Field2 Json Array C. Again for Loop to Iterate over Field4 Json Array D. Inside the nested for loop I've if condition to Match id value to "123" E. Store the Matching subdocument into List 2. Mongo Way A. Use Aggregation query to get the desired output from DB.No Loops and conditions in the Java side. B. Aggregation Query below stages I) $Match - match the ABC document II) $unwind - Field2 III) $unwind - Field4 IV) $match - Match the with id ( value is "123") V) $group - group the document based on Field3 (based on "ABC1" or "ABC2") VI) execute aggregation and return results
Both are working good and returning proper results.
Question is which one is the better to follow and why ? I used the aggregation in restful service get method, So executing aggregation queries 1000 or more times in parallel will cause any performance problems?