简体   繁体   中英

Need to convert this SQL query to MongoDB

I am new to MongoDB. I need to convert this SQL code to MongoDB

select TOP 5 r.regionName, COUNT(c.RegionID)
from region as r,
     company as c
where c.RegionID = r._id
group by r.regionName
order by COUNT(c.RegionID) DESC;

Option 1. You can use the aggregation framework with $lookup , $group , $project , $sort and $limit stages, but this seems like a wrong approach since the true power to change relation database with mongoDB is the denormalization and avoidance of join ( $lookup ) like queries.

Option 2. You convert your multi-table relational database schema to document model and proceed with simple $group , $project , $sort and $limit stage aggregation query for the above task.

Since you have not provided any mongodb document examples it is hard to provide how your queries will look like...

You should show attempt of converting it, as indicated in the comments.

You could try using an online converting tool, like this SQL Query to MongoDB Converter , it should work with simple queries. For your query, it returns:

db.regionas r, company as c .group({
   "key":{
         "r.regionName order by COUNT(c.RegionID) DESC": true
   },
   "initial": {
         "countc.RegionID":0
   },
   "reduce": function( obj , prev ){
         if (obj.c.RegionID != null ) if ( obj.c.RegionID instanceof Array)prev.countc.RegionID += obj.c.RegionID.length;
         else prev.countc.RegionID++;
   },
   "finalize": function( prev ){
   },
   "cond": {
 "$where": "this.c.RegionID  == this. r._id "
   }
});

I have not tested this, but I hope it serves as a starting point to build your query.

Despite of my comment I try to give a translation (not tested):

db.region.aggregate([
{
   $lookup: // left outer join collections
     {
       from: "company",
       localField: "_id",
       foreignField: "RegionID",
       as: "c"
     }
},
{ $match: { c: { $ne: [] } } }, // remove non-matching documents (i.e. INNER JOIN)
{ $group: { _id: "$regionName", regions: { $addToSet: { "$c.RegionID" } } } }, // group and get distinct regions
{ $project: { regionName: "$_id", count: { $size: "$regions" } , _id: 0} } // some cosmetic and count
{ $sort: { regionName: 1 } }, // order result
{ $limit: 5 } // limit number or returned documents
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM