mongodb数据存入及分析

MongoDB 是一个面向文档的 NoSQL 数据库,用于存储、检索和分析大量非结构化数据。以下是如何将数据存入 MongoDB 并进行基本分析的步骤:

1. 安装和启动 MongoDB

确保你已经安装了 MongoDB 并在你的系统上运行它。

2. 连接到 MongoDB

你可以使用 MongoDB 的 shell (mongo) 或者其他驱动程序(如 Python 的 pymongo)来连接到你的 MongoDB 数据库。

3. 选择或创建数据库和集合

在 MongoDB 中,数据存储在集合中,集合类似于关系型数据库中的表。集合又属于数据库。

实验环境

OS:Windows 10
Python3
MongoDB:v4.4

注意事项:

在代码的输入中需要注意大小写的切换,中文英文输入的切换,以及标点符号的切换,否则可能代码会报错

基本查询操作:

1.查询指定字段

可以使用MongoDB的投影查询来仅返回文档中特定的字段,减少数据传输量。

 

2.查询条件

支持各种比较操作符,如等于($eq)、不等于($ne)、大于($gt)、小于($lt)等,以及逻辑操作符如与($and)、或($or)、非($not)等,用于构建复杂的查询条件。

 

 3.正则表达式查询

MongoDB支持使用正则表达式进行模式匹配查询,可以灵活匹配字符串字段。

1.使用pymongo连接到MongoDB数据库:

from pymongo import MongoClient
 
# 创建MongoDB客户端实例
client = MongoClient('localhost', 27017)
 
# 选择数据库(如果不存在则自动创建)
db = client['myDatabase']
 
# 选择集合(如果不存在则自动创建)
collection = db['myCollection']

 2.插入数据:

# 插入一个文档
document = {
    'name': 'John Doe',
    'age': 30,
    'city': 'New York'
}
result = collection.insert_one(document)
print(f'Inserted document ID: {result.inserted_id}')
 
# 插入多个文档
documents = [
    {'name': 'Alice Smith', 'age': 25, 'city': 'San Francisco'},
    {'name': 'Bob Johnson', 'age': 35, 'city': 'Los Angeles'}
]
result = collection.insert_many(documents)
print(f'Inserted {len(result.inserted_ids)} documents')

3.查询数据:

# 查询所有文档
for doc in collection.find():
    print(doc)
 
# 查询年龄大于30的文档
for doc in collection.find({'age': {'$gt': 30}}):
    print(doc)

4.更新数据: 

	# 更新一个文档
result = collection.update_one({'name': 'John Doe'}, {'$set': {'age': 31}})
print(f'Matched {result.matched_count} documents and updated {result.modified_count} documents.')
 
# 更新多个文档
result = collection.update_many({'age': {'$lt': 30}}, {'$set': {'status': 'young'}})
print(f'Matched {result.matched_count} documents and updated {result.modified_count} documents.')

 5.删除数据:

	# 删除一个文档
result = collection.delete_one({'name': 'Alice Smith'})
print(f'Deleted {result.deleted_count} document.')
 
# 删除多个文档
result = collection.delete_many({'city': 'New York'})
print(f'Deleted {result.deleted_count} documents.')

 6.数据分析

使用聚合框架进行数据分析:
	# 计算所有用户的平均年龄
result = collection.aggregate([
    {'$group': {
        '_id': None,
        'averageAge': {'$avg': '$age'}
    }}
])
 
for doc in result:
    print(f'Average age: {doc["averageAge"]}')   

以上步骤将帮助你在mongodb进行简单的数据存入以及分析和查找

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值