MongoDB Middle Level (关联多表查询)

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]#./mongo
MongoDB shell version: 1.8.2
connecting 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,性能比分散存储要高且方便




原文链接: http://blog.csdn.net/crazyjixiang/article/details/6616678

转载于:https://my.oschina.net/chen106106/blog/51182

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值