MongoDB Query with groupby and condition and select

85 views
Skip to first unread message

ds.tov...@gmail.com

unread,
Dec 5, 2018, 6:03:43 PM12/5/18
to mongodb-user
am new to MongoDB , could you please convert below Query into MongoDB Query

SELECT ID, country, states, state_map
            FROM world
            WHERE state_status = 'Y'
            GROUP BY country
Each country should have multiple states.so states is a list.

Robert Cochran

unread,
Dec 5, 2018, 8:07:32 PM12/5/18
to mongodb-user
Hi! 

I think you would highly benefit by taking a MongoDB University class. Any one of the M101* series of courses will be very helpful to you. They are a lot of fun to take and give you an excellent grasp of MongoDB.

Thanks

Bob

Wan Bachtiar

unread,
Dec 11, 2018, 1:05:53 AM12/11/18
to mongodb-user

could you please convert below Query into MongoDB Query

Hi,

You can perform an aggregation query to group by using Aggregation Pipeline. Normally it’s better to provide the sample document structure and the desired output from the query, instead of providing SQL query.

Without knowing exactly the document structure and the desired output, an example pipeline for your query would be:

db.world.aggregate([
    {"$match": {"state_status": "Y"}}, 
    {"$group": {"_id": "$country", 
                "ID": {"$addToSet": "$ID"},
                "states": {"$addToSet":"$states"}, 
                "state_map": {"$addToSet":"$state_map"}, 
               }
    },
])

am new to MongoDB

As mentioned by Robert, I would also recommend to enrol in a free online course at MongoDB University to learn more about MongoDB. Especially M121: The MongoDB Aggregation Framework, to learn how to use MongoDB’s Aggregation. The next session is 8th January 2019, there is plenty of time to register.

See also SQL to Aggregation Mapping Chart

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages