MongoDB语法

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

https://www.runoob.com/mongodb/mongodb-aggregate.html

https://www.jianshu.com/p/5e870132ca7c

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值