程序员人生 网站导航

MongoDB: 3. Schema Design

栏目:综合技术时间:2013-11-09 04:55:53
1. Document-Oriented

MongoDB 是一种面向文档(document-oriented)的数据库,其内存储的是一种 JSON-like 结构化数据。尽管拥有和关系型数据库 Database/Table 类似的的 DB/Collection 概念,但同一 Collection 内的 Document 可以拥有不同的属性。

(注: 以下 > 提示符表示 mongo JS 代码,>>> 为 Python 代码)

> use blog
switched to db blog

> db.users.insert({name:"user1", age:15})
> db.users.insert({name:"user2", age:20, sex:1})

> db.users.find()
{ "_id" : ObjectId("4c479885089df9b53474170a"), "name" : "user1", "age" : 15 }
{ "_id" : ObjectId("4c479896089df9b53474170b"), "name" : "user2", "age" : 20, "sex" : 1 }
可以通过 $exists 判断某个字段是否存在。

> db.users.find({sex:{$exists:true}})
{ "_id" : ObjectId("4c479896089df9b53474170b"), "name" : "user2", "age" : 20, "sex" : 1 }
2. Embed vs. Reference

Document 采取 JSON-like 这种层级结构,因此我们可以直接用嵌入(Embed)代替传统关系型数据库的关联引用(Reference)。

> u = db.users.findOne({name:"user1"})
{
"_id" : ObjectId("4c479885089df9b53474170a"),
"name" : "user1",
"age" : 15
}

> u.address = ["address1", "address2"]
[ "address1", "address2" ]

> db.users.save(u)

> db.users.findOne({name:"user1"})
{
"_id" : ObjectId("4c479885089df9b53474170a"),
"name" : "user1",
"age" : 15,
"address" : [
"address1",
"address2"
]
}

> db.users.findOne({address:"address1"})
{
"_id" : ObjectId("4c479885089df9b53474170a"),
"name" : "user1",
"age" : 15,
"address" : [
"address1",
"address2"
]
}
MongoDB 支持以 "." 分割的 namespace 路径,但需要注意 key 不能以 "$" 开头,不能包含 "." 字符 (条件表达式中的多级路径须用引号)。

> u = db.users.findOne({address:"address1"})
{
"_id" : ObjectId("4c479885089df9b53474170a"),
"name" : "user1",
"age" : 15,
"address" : [
"address1",
"address2"
]
}

> u.im = {msn:"user1@hotmail.com", qq:12345678}
{ "msn" : "user1@hotmail.com", "qq" : 12345678 }

> db.users.save(u)

> u = db.users.findOne({"im.qq":12345678})
{
"_id" : ObjectId("4c479885089df9b53474170a"),
"name" : "user1",
"age" : 15,
"address" : [
"address1",
"address2"
],
"im" : {
"msn" : "user1@hotmail.com",
"qq" : 12345678
}
}

> u.im.qq
12345678

> u.im.msn
user1@hotmail.com

> db.users.update({"im.qq":12345678}, {$set:{"im.qq":12345}})

> u = db.users.findOne({"im.qq":12345})
{
"_id" : ObjectId("4c479885089df9b53474170a"),
"name" : "user1",
"age" : 15,
"address" : [
"address1",
"address2"
],
"im" : {
"msn" : "user1@hotmail.com",
"qq" : 12345
}
}

> u = db.users.find({"im.qq":{$exists:true}}, {"im.qq":1})
{ "_id" : ObjectId("4c479885089df9b53474170a"), "im" : { "qq" : 12345 } }
------分隔线----------------------------
------分隔线----------------------------

最新技术推荐