mongodb 集合操作

转自官方文档:http://docs.mongodb.org/manual/reference/sql-aggregation-comparison/

sql和mongodb集合操作对比

SQL 集合操作 MongoDB 集合操作
WHERE $match
GROUP BY $group
HAVING $match
SELECT $project
ORDER BY $sort
LIMIT $limit
SUM() $sum
COUNT() $sum
join 可以使用 $unwind实现类似操作,不过一般使用内嵌文档.


集合字段结构

{
  cust_id: "abc123",
  ord_date: ISODate("2012-11-02T17:04:11.102Z"),
  status: 'A',
  price: 50,
  items: [ { sku: "xxx", qty: 25, price: 1 },
           { sku: "yyy", qty: 25, price: 1 } ]}


SQL 语法 MongoDB 语法
SELECT COUNT(*) AS count FROM orders
db.orders.aggregate(
[{ $group: { _id: null, 
           count: { $sum: 1 } 
           } 
}] )
SELECT SUM(price) AS total FROM orders
db.orders.aggregate(
[{ $group: { _id: null, 
            total: { $sum: "$price" } } 
}] )
SELECT cust_id,
       SUM(price) AS total FROM orders
       GROUP BY cust_id
db.orders.aggregate(
[{ $group: { _id: "$cust_id", 
             total: { $sum: "$price" } } 
}] )
SELECT cust_id,
 SUM(price) AS totalF ROM orders
GROUP BY cust_id ORDER BY total
db.orders.aggregate( 
[   { $group: { _id: "$cust_id",
               total: { $sum: "$price" } } 
    },
    { $sort: { total: 1 } }
])
SELECT cust_id,
       ord_date,
       SUM(price) AS totalF ROM orders
       GROUP BY cust_id, ord_date
db.orders.aggregate(
[ { $group: { _id: { cust_id: "$cust_id", 
                    ord_date: "$ord_date" 
                   },
             total: { $sum: "$price" } } 
}] )
SELECT cust_id, count(*) FROM orders
GROUP BY cust_id HAVING count(*) > 1
db.orders.aggregate(
[{ $group: { _id: "$cust_id", 
            count: { $sum: 1 } } },
 { $match: { count: { $gt: 1 } }
}] )
SELECT cust_id,
       ord_date,
SUM(price) AS total FROM orders
GROUP BY cust_id, ord_date 
HAVING total > 250
db.orders.aggregate(
[{$group:{ _id:{cust_id: "$cust_id", 
                ord_date: "$ord_date" }, 
          total: { $sum: "$price" } } }, 
 {$match: { total: { $gt: 250 } } 
}] )
SELECT cust_id,
  SUM(price) as total FROM orders
WHERE status = 'A' GROUP BY cust_id
db.orders.aggregate(
[{$match:{ status: 'A' } }, 
{ $group:{ _id: "$cust_id", 
          total: { $sum: "$price" } } 
}] )
SELECT cust_id,
  SUM(price) as total FROM orders
  WHERE status = 'A'
  GROUP BY cust_id HAVING total > 250
db.orders.aggregate(
[{ $match:{ status: 'A' } },
 { $group: { _id: "$cust_id", 
            total: { $sum: "$price" } } }, 
 { $match: { total: { $gt: 250 } } 
 }] )
SELECT cust_id,
    SUM(li.qty) as qty FROM orders o,
     order_lineitem li
     WHERE li.order_id = o.id
     GROUP BY cust_id
db.orders.aggregate(
[{$unwind: "$items" }, 
 {$group: { _id: "$cust_id",
           qty: { $sum: "$items.qty" } } 
 }] )
SELECT COUNT(*)
FROM (SELECT cust_id, ord_date
FROM orders
GROUP BY cust_id, ord_date) as DerivedTable
db.orders.aggregate( 
[{$group:{ _id:{cust_id:"$cust_id",                      
           ord_date:"$ord_date"}}},   
 {$group: { _id: null, 
           count: { $sum: 1 } } 
}] )


你可能感兴趣的:(mongodb 集合操作)