{ "_id":ObjectId("52ffc33cd85242f436000001"), "name": "bianchengbang", "phone": "15011226666", "birth": "01-01-1991" }以下是记录用户地址的文档结构:
{ "_id":ObjectId("52ffc4a5d85242602e000000"), "place": "22 A, Indiana Apt", "postcode": 123456, "city": "Los Angeles", "country": "California" }
{ "_id" : ObjectId("603c8471f2c28d0fdf74ae78"), "phone" : "15011226666", "pincode" : "01-01-1991", "name" : "bianchengbang", "address" : [ { "place" : "22 A, Indiana Apt", "postcode" : 123456, "city" : "Los Angeles", "country" : "California" }, { "place" : "170 A, Acropolis Apt", "postcode" : 456789, "city" : "Chicago", "country" : "Illinois" } ] }这种将所有相关数据都保存在一个文档中的方式,可以使得文档的检索和维护变的更加容易,当我们要查询用户地址时,可以像下面这样:
> db.users.findOne({"name":"bianchengbang"},{"address":1}) { "_id" : ObjectId("603c8471f2c28d0fdf74ae78"), "address" : [ { "place" : "22 A, Indiana Apt", "postcode" : 123456, "city" : "Los Angeles", "country" : "California" }, { "place" : "170 A, Acropolis Apt", "postcode" : 456789, "city" : "Chicago", "country" : "Illinois" } ] }虽然这样的结构在读取数据时很方便,但这种数据结构也是有缺点的,当用户和用户地址不断增加,数据量不断变大时,会大大影响数据库的读写性能。
{ "_id" : ObjectId("603c8471f2c28d0fdf74ae78"), "phone" : "15011226666", "pincode" : "01-01-1991", "name" : "bianchengbang", "address_ids" : [ ObjectId("603c8471f2c28d0fdf74ae79"), ObjectId("603c8471f2c28d0fdf74ae80") ] }如上所示,在用户文档中包含一个 address_ids 字段,其中包含用户地址文档中相应的 ObjectId。使用这些 ObjectId,我们可以从用户地址文档中获取地址的详细信息。使用这种方法,我们将需要两次查询,第一次从用户文档中获取 address_ids 字段,第二次从地址集合中获取地址的详细信息。
> var ids = db.users.findOne({"name":"bianchengbang"},{"address_ids":1}) > var addresses = db.address.find({"_id":{"$in":ids["address_ids"]}}).pretty() > addresses { "_id" : ObjectId("603c9355f2c28d0fdf74ae79"), "place" : "22 A, Indiana Apt", "postcode" : 123456, "city" : "Los Angeles", "country" : "California" } { "_id" : ObjectId("603c937bf2c28d0fdf74ae7a"), "place" : "170 A, Acropolis Apt", "postcode" : 456789, "city" : "Chicago", "country" : "Illinois" }
本文链接:http://task.lmcjl.com/news/17670.html