MongoDB基础知识与操作
1、什么是mongoDB
MongoDB是面向文档的NoSQL数据库,经常被用于存储非关系型的数据库,常用MongoDB存储web服务日志,或用来存储爬虫内容
MySQL是数据库,SQL是领域型语言,操作数据库 2、MongoDb创建数据库 use database_name use test db show dbs
插入数据 Mongodb中没有直接创建表的命令,在MongoDb中,建完数据库后可以直接往表中插入数据,表名在插入数据时指定
db.collection.insert(doucment) db.user.insert({ ‘name’:‘chenwuyou’, ‘age’:25 })
在mongodb中等于、小于、小于等于、大于、大于等于、不等于
等于 db.col.find({“by”:“Mongodb入门教程”}).pretty() 小于 db.col.find({“likes”:{KaTeX parse error: Expected 'EOF', got '}' at position 6: lt:50}?}).pretty() 小于或…lte:50}}).pretty() 大于 db.col.find({“likes”:{KaTeX parse error: Expected 'EOF', got '}' at position 6: gt:50}?}).pretty() 大于或…gte:50}}).pretty() 不等于 db.col.find({“likes”:{$ne:50}}).pretty()
查询用户表中所有年龄大于等于25岁的用户,查询语句为: db.user.find({“age”:{$gte:25}},{“_id”:0}).pretty()
排序
在Mongodb中使用sort()方法对数据进行排序,sort()方法可通过参数指定排序的字段 db.collection.find().sort({key:1}) 1表示升序,-1表示降序
将所有年龄小于30岁的用户查询出来,并按照年龄升序排列 db.user.find({“age”:{KaTeX parse error: Expected 'EOF', got '}' at position 6: lt:30}?}).sort({age:1}…set:{‘age’:27}})
删除操作 db.col.remove({}) db.col.find()
python处理MongoDB
import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)
db = client.test
collection = db.user
people = {
'name':'chenwuyou',
'age':26,
'hobby':'code'
}
result = collection.insert_one(people)
print(result)
print(result.inserted_id)
people = {
'name':'chenwuyou',
'age':26,
'hobby':'code'
}
people1 = {
'name':'chenwuyou1',
'age':26,
'hobby':'code'
}
result = collection.insert_many([people,people1])
print(result)
print(result.inserted_ids)
result = collection.find_one({'name':'chenwuyou'})
print('result:',result)
from bson.objectid import ObjectId
result = collection.find_one({'_id':ObjectId('631c2a5afafd42348f0f4625')})
print(result)
results = collection.find({'age':{'$gt':20}})
for result in results:
print(result)
count = collection.estimated_document_count({'age':{'$gt':20}})
print(count)
results = collection.find().sort('name',pymongo.ASCENDING)
print([result['name']for result in results])
condition = {'name':'chenwuyou'}
people = collection.find_one(condition)
people['age'] = 28
result = collection.update_one(condition,{'$set':people})
print(result)
print(result.matched_count,result.modified_count)
|