--

MongoDB query data



MongoDB 是基于文件的数据库系统 (NoSQL)
获取数据的基本语法是:

db.collection.find(, ).



我们比较 SQL 与 MongoDB 的基本语法
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$/})
      


其中,MongoDB 的一些逻辑操作资料可以在下面链接查到
https://docs.mongodb.com/manual/reference/operator/query/ $eq
$gt
$gte
$lte
$ne
$in
$nin
$or
$and
$not
$nor


对于 array 的操作:

  // 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"}}
    ]
  })


aggregation

  获取 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


aggregation 有 Grouping,aggregate,functions,以及 sorting 等


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}}])



JOIN

  db.orders.aggregate([
    {$loopup: {
      from:"inventory",
      localField:"item",
      foreignField:"sku",
      as:"inventory_docs"
    }}]
  )

得到的结构应该是:


其中要注意的是,对于 _id = 3 的order,默认的 item 是 null,在 inventory中也是存在的(5, 6)。