mongodb的一些概念:
查询数据库列表:
show dbs
返回结果为空,因为目前还没有创建任何数据库。使用use
命令创建数据库,例如创建catalog
数据库:
use catalog
当创建新数据库时,里面没有创建collection,可以使用如下命令确认:
show collections
可以使用createCollection命令创建collection。
以下命令将在catalog数据库中创建新的collection(products
),并插入一条document:
db.products.insert({
"name" : "RayBan Sunglass Pro",
"sku" : "1590234",
"description" : "RayBan Sunglasses for professional sports people",
"inventory" : 100
})
DocumentDB返回成功插入document的数量:
insertMany
命令可以一次插入多个document:
db.products.insertMany([
{
"name" : "GUCCI Handbag",
"sku" : "3451290",
"description" : "Fashion Hand bags for all ages",
"inventory" : 75
},
{
"name" : "Round hat",
"sku" : "8976045",
"inventory" : 200
},
{
"name" : "Polo shirt",
"sku" : "6497023",
"description" : "Cool shirts for hot summer",
"inventory" : 25
},
{
"name" : "Swim shorts",
"sku" : "8245352",
"description" : "Designer swim shorts for athletes",
"inventory" : 200
},
{
"name" : "Running shoes",
"sku" : "3243662",
"description" : "Shoes for work out and trekking",
"inventory" : 20
}
])
返回插入的ObjectId。注意这个ObjectId是DocumentDB自动生成的,在query操作时会返回不同的值。
可以使用以下命令来读取插入到DocumentDB中的数据,find命令中指定了过滤的条件,pretty命令用于优化结果的展示(如果不加会把结果放到一行显示)。
db.products.find({"sku":"1590234"}).pretty()
返回以下结果:
使用find命令时,如果不加查询的条件,会返回前20条document。
rs0:PRIMARY> db.products.find().pretty()
{
"_id" : ObjectId("61a2f7cc5e0271eedc932907"),
"name" : "RayBan Sunglass Pro",
"sku" : "1590234",
"description" : "RayBan Sunglasses for professional sports people",
"inventory" : 100
}
{
"_id" : ObjectId("61a2f8635e0271eedc932908"),
"name" : "GUCCI Handbag",
"sku" : "3451290",
"description" : "Fashion Hand bags for all ages",
"inventory" : 75
}
{
"_id" : ObjectId("61a2f8635e0271eedc932909"),
"name" : "Round hat",
"sku" : "8976045",
"inventory" : 200
}
{
"_id" : ObjectId("61a2f8635e0271eedc93290a"),
"name" : "Polo shirt",
"sku" : "6497023",
"description" : "Cool shirts for hot summer",
"inventory" : 25
}
{
"_id" : ObjectId("61a2f8635e0271eedc93290b"),
"name" : "Swim shorts",
"sku" : "8245352",
"description" : "Designer swim shorts for athletes",
"inventory" : 200
}
{
"_id" : ObjectId("61a2f8635e0271eedc93290c"),
"name" : "Running shoes",
"sku" : "3243662",
"description" : "Shoes for work out and trekking",
"inventory" : 20
}
使用$set
操作符,在之前的document中新增一个reviews
字段,它是一个数组结构,包括review
和rating
两个属性:
db.products.update(
{"sku":"1590234"},
{
$set: {
"reviews" : [{
"rating" :4,
"review":"perfect glasses"
},{
"rating" :4.5,
"review":"my prized possession"
},{
"rating" :5,
"review":"Just love it"
}]}
}
)
返回matched, upserted, modified
的document数量:
可以再读取这条document,确认更改生效:
db.products.find({"sku":"1590234"}).pretty()
使用remove命令删除document:
db.products.remove({"sku":"8976045"})
返回被删除的document数量: