0

Hi i want to get the distict values in mongodb.

this is my example table

Name________________Age___________________Salary

x ___________________ 25 ___________________5000

x ___________________ 25 ___________________5000

x ___________________ 26 ___________________5000

y ___________________ 25 ___________________5000

y ___________________ 26 ___________________5000

I want to get the result like this

    {

        "Name" : "x",
    "Age" : [ 
            {
                25,26

            }]
    }

{

        "Name" : "y",
    "Age" : [ 
            {
                25,26

            }]
    }

is there any way to get the result like this.

my sql query is

select distinct Name,Age from Table where salary=5000

i tried like this

but this is not able to get like this

db.getCollection('Table').aggregate([
{"$match":{Salary:5000}},
{"$group":{_id:{Name:"$Name",Age:"$Age"}}},
{"$project" : {_id:0, Name:"$_id.Name", Age:"$_id.Age"}}
])

1 Answer 1

2

Use $addToSet for distinct Age when $grouping on Name to get the desired output.

db.getCollection('Table').aggregate([
{"$match":{Salary:5000}},
{"$group":{_id:"$Name", "Age":{$addToSet:"$Age"}}},
{"$project" : {_id:0, Name:"$_id", Age:1}}
])
Sign up to request clarification or add additional context in comments.

4 Comments

Hi veeram I have one doubt in MongoDB query. Select (Distinct Name),Age,Salary from Table. I want to get Name only distinct, either column are not want to show as distinct but i want to show all the columns as per without distinct including _id column value. Can you give me the answer
Use $push for each of the column in the group. Something like "Salary":{"$push":"$Salary"}
where should i give the query. Can you add this answer for "Salary and Age"column
Something like {"$group":{_id:"$Name", "Age":{$push:"$Age"}, Salary ...}},

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.