当前位置:网站首页>如何向mongoDB中添加新的字段附代码(全)
如何向mongoDB中添加新的字段附代码(全)
2022-07-05 21:52:00 【码农研究僧】
前言
关于MongoDB更多的知识点可看我之前这篇文章:
MongoDB框架零基础入门
本身MongoDB的连接就和Mysql的数据库一样
Mysql连接方式:mysql -u -root -p(标准模式下)
MongoDB类似:mongo -u root -p
之所以要增加字段值
一般都是python web框架中,在form表单内增加了一个字段值写入数据库(只有最新的数据才有这个字段值)
之前数据没有的字段值只能通过数据库添加
具体添加方式可以通过数据库内或者脚本一键添加(两种方式都差不多)
1. 数据库内增加
在数据库内增加字段值
通过update增加即可
通过mongo连接上(区分版本号、用户名、密码、文档集合、端口号等)
我的连接方式为:mongo版本号 --host xxx -u 用户名 -p "密码" 文档集合 --port 端口号
链接上去之后就会显示mongo命令入口(类似mysql)
在该数据库增加所要的文档集合字段值
增加的同时为了保守起见,先通过find查询是否有该字段
格式如下:db.文档集合.find({字段值字典}).pretty()
代码示例如下:
db.manong.find({"age":18}).pretty()
查询到该字段值有值之后对其update更新添加某个字段值
格式如下:db.collection.update({query},{$set:{"":""}})
db.manong.update({
"age":18},{
$set:{
'title':'码农- 研究僧'}})
再通过find进行查询是否有该字段值
如果是所有的数据都增加这个字段值为'title':'码农- 研究僧'
则代码如下:
db.manong.update({
},{
$set:{
'title':'码农- 研究僧'}})
2. 脚本添加
通过脚本一键修改的方式比较保守保险
主要是终端稍微打错命令回车可能会造成致命错误
具体的脚本只需要连接mongo、查询mongo是否有该数据值(debug)、对应添加新的字段值
(所有的数据中都增加这个字段值)完整代码如下:
import datetime
from django.core.management.base import BaseCommand
# 引入连接mongo的函数,写在外部,就不在代码中放连接函数
from xx.common import get_mongo
class Command(BaseCommand):
def handle(self, *args, **options):
# 连接mongo
mongo = get_mongo()
values = {
"$set": {
"title":"码农- 研究僧"
}
}
mongo["集合"].update({
}, values, multi=True)
# debug查询显示值
for record in mongo["集合"].find():
logger.info(record)
通过python xx.py(文件名)执行该脚本
如果设置了虚拟环境执行脚本
具体可看我这篇文章:
Windows配置虚拟环境以及常用命令(图文解析)
另外一种情况就是:
对应某个数据增加这个字段值的脚本如下:(核心代码)
params = {
"age": 18
}
values = {
"$set": {
"title":"码农- 研究僧"
}
}
mongo["集合"].update(params, values)
# debug查询显示值
for record in mongo["集合"].find():
logger.info(record)
边栏推荐
- Zhang Lijun: penetrating uncertainty depends on four "invariants"
- datagrid直接编辑保存“设计缺陷”
- JMeter installation under win7
- Some things make feelings nowhere to put
- 多家呼吸机巨头产品近期被一级召回 呼吸机市场仍在增量竞争
- Interview questions for basic software testing
- CRM creates its own custom report based on fetch
- 从零开始实现lmax-Disruptor队列(四)多线程生产者MultiProducerSequencer原理解析
- Multiplexing of Oracle control files
- Problems encountered in office--
猜你喜欢
随机推荐
Some common processing problems of structural equation model Amos software
如何组织一场实战攻防演练
ICMP 介绍
Simple interest mode - lazy type
他们主动布局(autolayout)环境的图像编辑器
Robot operation mechanism
从零开始实现lmax-Disruptor队列(四)多线程生产者MultiProducerSequencer原理解析
华为联机对战如何提升玩家匹配成功几率
Cold violence -- another perspective of objective function setting
The primary key is set after the table is created, but auto increment is not set
MMAP
matlab绘制hsv色轮图
Four components of logger
Recursive query of multi-level menu data
Poj3414广泛搜索
SQL common syntax records
阿龙的感悟
Chap2 steps into the palace of R language
123456
MMAP learning









