MongoDB 是基于文件的数据库系统 (NoSQL)
获取数据的基本语法是:
db.collection.find(, ).
SQL | MongoDB |
---|---|
SELECT * from Bears |
db.Beers.find() |
SELECT beer, price FROM Sells |
db.Sells.find( {}, {beer:1, price: 1} ) |
SELECT manf FROM Beers WHERE name = 'heineken' |
db.Beers.find( {name:'heineken'}, {manf: 1, _id: 0} ) |
SELECT DISTINCE beer, price FROM Ssells WHERE price > 15 |
db.Sells.distinct( {price: {$gt:15}}, {beer:1, price: 1, _id:0} ) |
|
sb.Beers.find( name: {$regex: /am/i}).count() |
|
db.Beers.find( name: {$regex: /^Am/}).count() |
db.Beers.count(name: {$regex: /^Am.*corp$/}) |
// find items which are tagged as 'popular' or 'organic' db.inventory.find({tags: {$in: ["popular", "organic"]}}) // find items which are not tagged as 'popular' nor 'organic' db.inventory.find({tags: {$nin: ["popular", "organic"]}}) // find the 2nd and 3rd elements of tags db.inventory.find({}, {tags: {$slice: [1,2]}}) db.inventory.find({}, tags: {$slice: -2}) // find a document whose 2nd element in tags is 'summer' db.inventory.find(tags.1: "summer") db.inventory.find({ $and: [ {$or: [{price: 3.99}, {price: 4.99}]}, {$or: [{rating: good}, {qty: {$lt: 20}}]} {item: {$ne: "Coors"}} ] })
获取 drinker 总和数目 db.Drinkers.count() 获取 drinker 的 addr 的数目 db.Drinkers.count(addr:{$exists: true}) 获取distinct 的数目 // raw data Data :{_id: 1, places: [USA, France, USA, Spain, UK, Spain] } db.countryDB.distinct(places) ==> return [USA, France, Spain, UK] db.countryDB.distinct(places).length ==> return 4
db.computers.aggregate( [ { $group : { _id: {brand: "$brand", title: "$title", category: "$category", code: "$code"}, count: {$sum: 1} } } { $sort: {count: 1, category: -1} }] )
db.articles.aggregate( [ {$match: {$text: {$search: "Hillary Democrat"}}}, {$sort: {score: {$meta: "textScore"}}}, {$project: {title: 1, _id: 0}}])
db.orders.aggregate([ {$loopup: { from:"inventory", localField:"item", foreignField:"sku", as:"inventory_docs" }}] )