MongoDB学习第三篇 --- Insert操作
一、shell操作mongodb
1.新增一条数据 : db.collection.insertOne(‘json对象’)
eg:
db.inventory.insertOne( { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } } )
2.新增多条数据 : db.collection.insertMany(‘json数组’)
eg:
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" } } ])
3.新增一条或多条数据: db.collection.insert('数据')
eg:
db.inventory.insert( { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } } )
一、python操作mongodb(pymongo模块)
1.导入模块并连接数据库
import pymongo # 获取链接 connect =pymongo.MongoClient("127.0.0.1",27017) # 获取数据库 db_Malcolm = connect.malcolm # 获取表 collection = db_Malcolm.malcolm
2.insert操作
1)插入一条记录
db.inventory.insert_one( {"item": "canvas", "qty": 100, "tags": ["cotton"], "size": {"h": 28, "w": 35.5, "uom": "cm"}})
2)插入多条记录
db.inventory.insert_many([ {"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"}}])
3)新增一条或多条记录
collection.insert({"name":"Malcolm","age":34,"address":"台湾 台北","role":"programmer"})
一、java操作mongodb
java需要导入mongodb-driver-3.4.2.jar 和 mongo-java-driver-3.4.2.jar 包
1.插入一个document:
Document canvas = new Document("item", "canvas") .append("qty", 100) .append("tags", singletonList("cotton")); Document size = new Document("h", 28) .append("w", 35.5) .append("uom", "cm"); canvas.put("size", size); collection.insertOne(canvas);
2.插入多个document:
Document journal = new Document("item", "journal") .append("qty", 25) .append("tags", asList("blank", "red")); Document journalSize = new Document("h", 14) .append("w", 21) .append("uom", "cm"); journal.put("size", journalSize); Document mat = new Document("item", "mat") .append("qty", 85) .append("tags", singletonList("gray")); Document matSize = new Document("h", 27.9) .append("w", 35.5) .append("uom", "cm"); mat.put("size", matSize); Document mousePad = new Document("item", "mousePad") .append("qty", 25) .append("tags", asList("gel", "blue")); Document mousePadSize = new Document("h", 19) .append("w", 22.85) .append("uom", "cm"); mousePad.put("size", mousePadSize); collection.insertMany(asList(journal, mat, mousePad));
Insert操作:
1.如果collection不存在,会自动创建此collection
2._id 字段:在MongoDB中,每一个存储到collection中的记录称之为文档。 每一个文档都需要把唯一的 _id 字段当做主键。如果插入的文档没有 _id字段,系统会自动创建。
3.在MongoDB中,所有的写操作在单文档级别都是自动提交的,