MongoDB Insert Documents

  • centos7安装mongodb教程:centos7安装mongodb
  • 官网demo:Insert Documents
  • insertOne插入一个文档
  • insertMany插入多个文档
  • insert插入一或多个文档
  • python操作mongodb插入文档
  • 点击查看scrapy爬取鬼故事,数据存入mongodb实战
  • 显示数据库和集合
# 显示数据库
show dbs;
# 要执行下面的语句切换到数据库再执行查看集合
use test;	# 切换到test数据库
show collections;	# 查看test数据库的集合
# 显示数据
db.<collection>.find();

  • 插入文档的方法有三种(文档指的是数据,下同)
# 插入一个文档
db.collection.insertOne()
# 插入多个文档
db.collection.insertMany()
# 即可插入一个文档,也可以插入多个文档
db.collection.insert()

MongoDB Insert Documents_第1张图片

  • 插入一个文档insertOne(),接受一个字典
use test;	# 切换到test数据库

db.inventory.insertOne(
   { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)

show colletions;	# 查看当前数据库的集合
db.inventory.find()		# 查看inventory集合的文档

MongoDB Insert Documents_第2张图片

  • 插入多个文档insertMany()接受一个列表,列表里面是多个字典
db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
   { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
   { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])

MongoDB Insert Documents_第3张图片

  • insert(),即可接受一个字典,也可接受一个列表,列表放多个字典
db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)
# 插入一个文档
db.products.insert( { item: "card", qty: 15 } )

在这里插入图片描述

# 插入多个文档
db.products.insert(
   [
     { _id: 11, item: "pencil", qty: 50, type: "no.2" },
     { item: "pen", qty: 20 },
     { item: "eraser", qty: 25 }
   ]
)

MongoDB Insert Documents_第4张图片


python操作mongodb插入文档

1. 安装pymongo模块
pip install -i https://pypi.douban.com/simple pymongo

MongoDB Insert Documents_第5张图片

import pymongo


class MyMongo:
    def __init__(self):
    	# 链接mongodb数据库
        self.client = pymongo.MongoClient(host='192.168.19.128', port=27017)
        # 两种方法都可以链接指定数据库
        self.db = self.client.test  # 链接test数据库
        # self.db = self.client['test']  # 链接test数据库

    def insert(self):
   		# 再python操作中不推荐直接使用insert插入数据
        # resp = self.db.inventory.insert({'hehe': 'hehe'})
        # 推荐使用insert_one()插入单个文档,或者使用insert_many()插入多个文档
        resp = self.db.inventory.insert_one({'hehe': 'hehe'})
        print(resp)

    def close(self):
        self.client.close()
        print('mongodb已关闭')


if __name__ == '__main__':
    mon = MyMongo()
    mon.insert()
    mon.close()

MongoDB Insert Documents_第6张图片

# 插入多个文档也是一个列表,列表里面有多个字典
resp = self.db.inventory.insert_many([{
	'haha': 'haha'
}, {
	'aaa': 'aaa'
}, {
	'bbb': 'bbb'
}])

MongoDB Insert Documents_第7张图片

  • 关于链接数据库还有个方法,使用URI链接
class MyMongo:
    def __init__(self):
        # URI
        # self.uri = 'mongodb://username:password@host:port'
        # 因为没有用户名和密码,所以不用填
        self.uri = 'mongodb://192.168.19.128:27017'
        self.client = pymongo.MongoClient(self.uri)
        self.db = self.client.test

MongoDB Insert Documents_第8张图片

你可能感兴趣的:(mongodb)