python pymongo使用mongodb入门

python 使用mongodb是通过pymongo进行操作的

安装:
pip install pymongo
连接
client = MongoClient('mongodb://localhost:27017/')
创建db或连接db
client.test_database
client['test-database']
db = client.get_database("db_name")

认证:

db.authenticate('username', 'password')
创建集合collection 或获取集合
db.test_collection
db['test-collection']
查看集合
db.list_collection_names()
新增
init_data = {"author": "tom", "text": "My first blog post!",
             "tags": ["mongodb", "python", "pymongo"],
             "date": datetime.datetime.utcnow()}

post_id = collection.insert_one(init_data).inserted_id

print post_id
查询单文档

可以根据条件进行查询, 也可以使用projectid进行查询,注意: project不是简单的str字符串

print collection.find_one({"_id": post_id})

print collection.find_one({"author": "Mike"})

使用projectid查询

from bson.objectid import ObjectId


def get(post_id):
    # Convert from string to ObjectId:
    document = client.db.collection.find_one({'_id':ObjectId(post_id)})

print collection.find_one({"_id": ObjectId("xkkwow1919")})

批量插入:
muilt_data = [{"author": "Mike",
               "text": "Another post!",
               "tags": ["bulk", "insert"],
               "date": datetime.datetime(2009, 11, 12, 11, 14)},
              {"author": "Eliot",
               "title": "MongoDB is fun",
               "text": "and pretty easy too!",
               "date": datetime.datetime(2009, 11, 10, 10, 45)}]


result = collection.insert_many(muilt_data)

print result.inserted_ids
查询多个文档
collection_data = collect
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值