欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MongoDB创建数据库和集合实例(多种方法创建)

程序员文章站 2022-05-18 20:26:03
...

加粗样式

  1. 查看数据库
    使用 show dbs
  2. 创建教材的library数据库
    Use library
  3. 在library数据集中增加集合和文档
    使用多种方法实现对media集合中插入文档,具体数据如下:

方法1:定义变量,使用insert()或者insertOne()当变量为参数

var document=(
{Type:"book",
Title:"Definitive Guide to MongoDB 3rd ed.,The",
ISBN:"978-1-4842-1183-0",
Publisher:"Apress",
Author:["Hows, David","Plugger,Eelco","Membrey,Peter","Hawkins,Tim"]
}
)
db.media.insert(document)

方法2:记录直接作为函数参数

db.media.insert(
{Type:"CD",
Artist:"Nirvana",
Title:"Nevemind`",
Tracklist:[
{Track:"1",
 Title:"Smells like Teen Spirit",
 Length:"5:02"
},
{Track:"2",
 Title:"In Bloom",
 Length:"4:15"
}
]
}

方法3:使用高级语言的循环实现一次性插入多条记录

var document=[
  {Type:"book",
Title:"Definitive Guide to MongoDB 3rd ed.,The",
ISBN:"978-1-4842-1183-0",
Publisher:"Apress",
Author:["Hows, David","Plugger,Eelco","Membrey,Peter","Hawkins,Tim"]},
{Type:"CD",
Artist:"Nirvana",
Title:"Nevemind`",
Tracklist:[
 {Track:"1",
 Title:"Smells like Teen Spirit",
 Length:"5:02"},
{Track:"2",
 Title:"In Bloom",
 Length:"4:15"}
              ] }];
for(var i = 0;i<document.length;i++){
	db.media.insert(document[i])
}

方法4:使用insertMany()函数一次性插入多行文档

db.media.insertMany([
  {Type:"book",
Title:"Definitive Guide to MongoDB 3rd ed.,The",
ISBN:"978-1-4842-1183-0",
Publisher:"Apress",
Author:["Hows, David","Plugger,Eelco","Membrey,Peter","Hawkins,Tim"]},
{Type:"CD",
Artist:"Nirvana",
Title:"Nevemind`",
Tracklist:[
 {Track:"1",
 Title:"Smells like Teen Spirit",
 Length:"5:02"},
{Track:"2",
 Title:"In Bloom",
 Length:"4:15"}] );
  1. 查看集合中的文档数据
    db.media.find()
    db.media.count()
  2. 文档数据的删除
    db.media.remove({})
  3. 集合的删除
    db.media.drop()
  4. 数据库的删除
    在当前操作的焦点数据库下使用db.dropDatabase()
相关标签: MongoBD大数据处理