MongoDB介绍
MongoDB是文档型的NoSQL数据库,数据以文档(对应关系型数据库的记录)的形式在MongoDB中保存,文档实际上就是一个个JSON字符串,使用JSON的好处是非常直观,通过一系列的Key-Value键值对来表示数据,符合我们的阅读习惯。
在Java、Python中对JSON都有很好的支持,数据从MongoDB中读取出来后,可无需转换直接使用;支持丰富的数据结构,Value可以是普通的整型、字符串、数组、嵌套的子文档,使用嵌套的好处是在MongoDB中仅需一次简单的查询就能够获取到你所需的数据。
python 连接mongodb
import pymongo
# 连接数据库
conn = pymongo.MongoClient(host='***.***.*.*', port=*****, username='name', password='******')
# 指定要操作的数据库 --1688选品库
# dbname = '1688选品库'
# db = conn.dbname
db = conn['1688选品库']
# 限定数据库表 --dld_测试1021
df_asin = db['dld_测试1021']
dataframe = pd.DataFrame(list(df_asin.find()))
conn.close()
MongoDB语法
增
常用的插入文档方法包括:
db.collection.insertOne():插入单个文档
db.collection.insertMany():插入多个文档
db.collection.save():类似于 insertOne()。如果文档存在,则该文档会被更新;如果文档不存在,则会插入一个新文档。
db.getCollection('表名').insert(
{title: 'MongoDB例子',
description: '这是一个插入文档的MongoDB例子',
url: '[http://www.test.com'](http://www.test.com'/);,
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100}
)
删
db.getCollection('表名').remove({'title':' MongoDB例子'})
改
db.getCollection('表名').update({'title':'MongoDB 教程'},{$set:{'title':' MongoDB更新后的例子'}})
查
1、常用查询并排序
db.getCollection('表名').find({"name" : "测试套餐1111"}).sort({"createDate":-1})
注:1为升序,-1为降序
2、多条件or查询
db.getCollection('UserEntity').find({$or:[{"phone" : "18700000000"},{"phone" : "13400000000"}]})
3、多条件and查询
db.getCollection('UserEntity').find({"phone" : "18700000000","phone" : "13400000000"})
4、模糊查询
db.getCollection('UserEntity').find({"name" : /测试/})
5、查询去重后name列数据
db.getCollection('UserEntity').distinct("name")
6、只查询5条数据
db.getCollection('UserEntity').find().limit(5)
7、查询5-10之间数据
db.getCollection('UserEntity').find().limit(10).skip(5)
8、查询记录条数
db.getCollection('UserEntity').find().count()
9、分组查询
//单个字段分组查询
db.getCollection('UserEntity').aggregate([{$group : {_id : "$balance", num : {$sum: 1}}}])
//多个字段分组查询
db.getCollection('UserEntity').aggregate([{$group : {_id : {balance:"$balance",expressInc:"$expressInc"}, num : {$sum : 1}}}])
条件查询:
> $gt , >= $gte, < $lt, <= $lte, != $ne
db.tianyc02.find({age:{$lt:100,$gt:20}})
$in ,$nin
db.tianyc02.find({age:{$in:[11,22]}})
db.tianyc02.find({age:{$nin:[11,22]}})
注:gt=greater than lt=less than ne=not equal
参考链接:
https://www.cnblogs.com/mao2080/p/9570909.html