tech_post icon indicating copy to clipboard operation
tech_post copied to clipboard

mongo cheatsheet

Open Alexis374 opened this issue 9 years ago • 0 comments

  • MongoDB stores documents in collections. similar to table
  • mongoimport --db test --collection restaurants --drop --file ~/downloads/primer-dataset.json
  • If you attempt to add documents to a collection that does not exist, MongoDB will create the collection for you
  • equality query: top filed: db.restaurants.find( { "borough": "Manhattan" } ); embeded filed: db.restaurants.find( { "address.zipcode": "10075" } )
db.restaurants.find(
   { $or: [ { "cuisine": "Italian" }, { "address.zipcode": "10075" },{'grades.grade':{'$gt':20}} ] }
)
  • update:
db.restaurants.update(
    { "name" : "Juni" },  // find the first that matches this condition
    {
      $set: { "cuisine": "American (New)" },
      $currentDate: { "lastModified": true }
    },
     //{ 
         multi: true,
         upsert:true // if no matches ,insert a new document

         }
)

//replacement
db.restaurants.update(
   { "restaurant_id" : "41704620" },
   {
     "name" : "Vella 2",
     "address" : {
              "coord" : [ -73.9557413, 40.7720266 ],
              "building" : "1480",
              "street" : "2 Avenue",
              "zipcode" : "10075"
     }
   }
)

//multi write interleave,  use $isolated operator


db.restaurants.remove()  //remove all documents
db.restaurants.drop() // remove all documents and indexes
  • 多个文档构成集合,多个集合组成数据库。
  • 格式相同的文档应放在同一个集合(对管理,查询,索引都有好处)。
  • 一个mongo实例可承载多个数据库。数据库名对应磁盘上同名文件,每个数据库有独立的权限。
  • shell 用法
show collections
show users
show profile
  • mongo 有32位整数 64位整数 64位浮点数,而shell只有64位浮点数一种形式。
  • _id的默认类型是ObjectId,12字节,每个字节是2个十六进制数,故是24位长的字符串。ObjectId是由时间戳,机器标识符,PID, 计数器组成,可以保证同一秒中不同机器不同进程产生的ID是唯一的,同一秒钟相同机器相同进程可以产生2^24个不同的ObjectId, _id是由客户端驱动程序生成的,节省开销,同时可以方便地知道自己生成的Id
  • 插入:db.foo.insert({'bar':'baz'}),也可以传入个数组批量加入。插入原理:数据转成bson,然后插入,避免注入攻击。
  • 删除:db.foo.remove({'bar':'baz'}),删除符合条件的,若不指定条件,将collection内容全部删除,collection保留,索引保留。 db.drop_collection('foo'),索引被删除。
  • 更新:分为文档替换和文档。
//文档替换
//foo = {name:'foo',age:1}
var foo = db.foo.findOne({name:'foo'});
foo.age+=1
db.foo.update({name:'foo'},foo)
//文档更新
db.foo.update({'name':'foo'},{$inc:{age:1}})

常用修改器: $set: 可以修改键和内嵌文档的键 $unset:删除键

db.update({name:'foo'},{$set:{'favorate book':'js',},$unset:{'age':1}})

Alexis374 avatar Jun 30 '16 10:06 Alexis374