DBRef is a more formal specification for creating references between documents. DBRefs (generally) include a collection name as well as an object id. Most developers only use DBRefs if the collection can change from one
document to the next. If your referenced collection will always be the same, the manual references outlined above are more efficient.
^_^[root@:/usr/local/mongodb/bin]#./mongoMongoDB shell version: 1.8.2connecting to: test> var a = {name:"C++"} > db test> db.language.save(a)> db.language.find(){ "_id" : ObjectId("4da32c897d2de864e0448e06"), "name" : "C++" }> var b = {name:"javascript"}> db.language.save(b)> db.language.find(){ "_id" : ObjectId("4da32c897d2de864e0448e06"), "name" : "C++" }{ "_id" : ObjectId("4da32cb17d2de864e0448e07"), "name" : "javascript" }> lan = {name:"obj1",computer:[new DBRef('language',a._id)]}{ "name" : "obj1", "computer" : [ { "$ref" : "language", "$id" : ObjectId("4da32c897d2de864e0448e06") } ]}> lan.computer[0]{ "$ref" : "language", "$id" : ObjectId("4da32c897d2de864e0448e06") }> lan.computer[0].fetch(){ "_id" : ObjectId("4da32c897d2de864e0448e06"), "name" : "C++" }> db.language.insert(lan) > db.language.find(){ "_id" : ObjectId("4da32c897d2de864e0448e06"), "name" : "C++" }{ "_id" : ObjectId("4da32cb17d2de864e0448e07"), "name" : "javascript" }{ "_id" : ObjectId("4da33b487d2de864e0448e08"), "name" : "obj1", "computer" : [ { "$ref" : "language", "$id" : ObjectId("4da32c897d2de864e0448e06") } ] }> db.language.findOne({name:"obj1"}).computer[0].fetch() { "_id" : ObjectId("4da32c897d2de864e0448e06"), "name" : "C++" }> lan2 = {name:"obj2",computer:[new DBRef('language',b._id)]} { "name" : "obj2", "computer" : [ { "$ref" : "language", "$id" : ObjectId("4da32cb17d2de864e0448e07") } ]}> db.language.insert(lan2)> db.language.find(){ "_id" : ObjectId("4da32c897d2de864e0448e06"), "name" : "C++" }{ "_id" : ObjectId("4da32cb17d2de864e0448e07"), "name" : "javascript" }{ "_id" : ObjectId("4da33b487d2de864e0448e08"), "name" : "obj1", "computer" : [ { "$ref" : "language", "$id" : ObjectId("4da32c897d2de864e0448e06") } ] }
相關資料存放在一起,針對性的查詢可以消除join,效能比分散儲存要高且方便