码迷,mamicode.com
首页 > 数据库 > 详细

mongodb和python交互

时间:2018-11-05 19:14:29      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:any   删除   批量   from   批量增加   host   pip   pymongo   date   

一、安装pymongo包

  sudo pip install pymongo

二、新增数据:

  增加一条:

      from pymongo import MongoClient 

      client = MongoClient(host = ‘127.0.0.1‘, port = 27017)
      collection = client[‘test1‘][‘t1‘]
      ret = collection.insert({‘name‘: ‘zs‘, ‘age‘: 30})
      print(ret)

  批量增加:

      from pymongo import MongoClient 

      client = MongoClient(host = ‘127.0.0.1‘, port = 27017)
      collection = client[‘test1‘][‘t1‘]
      item_list = [{‘_id‘: ‘101{}‘.format(i)} for i in range(10)]
      t = collection.insert_many(item_list)
      for j in t.inserted_ids:
        print(j)

三、查询数据

  查询一条:

    from pymongo import MongoClient

    client = MongoClient(host = ‘127.0.0.1‘, port = 27017)
    collection = client[‘test1‘][‘t1‘]
    t = collection.find_one({‘_id‘: ‘1001‘})
    #t = collection.find_one()
    print(t)

  查询所有:

    from pymongo import MongoClient

    client = MongoClient(host = ‘127.0.0.1‘, port = 27017)
    collection = client[‘test1‘][‘t1‘]
    t = collection.find()
    for i in t:  (t是游标,只能遍历一遍)
      print(i)

    for i in t:    //这里不会输出任何数据
      print(i)  //这里不会输出任何数据

四、更新数据

  更新一条:

    collection.update_one({‘name‘:‘upoo‘}, {"$set":{‘name‘:‘yyuu‘}})

  更新全部:

    collection.update_many({‘name‘:‘upoo‘}, {‘$set‘:{‘name‘:‘yyuu‘}})

五、删除数据

  删除一条:

    collection.delete_one({‘name‘: ‘yyuu‘})

  删除多条:

    collection.delete_many({‘name‘: ‘yyuu‘})

 

mongodb和python交互

标签:any   删除   批量   from   批量增加   host   pip   pymongo   date   

原文地址:https://www.cnblogs.com/DonCharles/p/9910431.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!