How to write Custom Query for Mongo DB to get the distinct data Need to write in Java but I need to check if is it possible with the query as well without using aggregation pipeline. Sample Data:
[
{
"id":1,
"empName":"emp1",
"emp_city":"city1"
},
{
"id":2,
"empName":"emp2",
"emp_city":"city1"
},
{
"id":3,
"empName":"emp1",
"emp_city":"city1"
},
{
"id":4,
"empName":"emp1",
"emp_city":"city2"
}
]
Expected Output:
[
{
"empName":"emp1",
"emp_city":"city1"
},
{
"empName":"emp1",
"emp_city":"city2"
},
{
"empName":"emp2",
"emp_city":"city1"
}
]
CodePudding user response:
For what you are trying to archive I would suggest using a group by, by the two fields (empName and emp_city),
Here you have and example https://sqlserverguides.com/mongodb-group-by-multiple-fields/
CodePudding user response:
use this :
db.collection.aggregate([
{
$group: {
_id: {
empName: "$empName",
emp_city: "$emp_city"
}
}
},
{
"$replaceRoot": {
"newRoot": "$_id"
}
}
])