利用DBREF实现MongoDB的引用("外键")
2015-10-02 19:07
471 查看
Using DBRefs
There are three fields in DBRefs:$ref: This field specifies the collection of the referenced document
$id: This field specifies the _id field of the referenced document
$db: This is an optional field and contains name of the database in which the referenced document lies
Consider a sample user document having DBRef field address as shown below:
{ "_id":ObjectId("53402597d852426020000002"), "address": { "$ref": "address_home", "$id": ObjectId("534009e4d852427820000002"), "$db": "tutorialspoint"}, "contact": "987654321", "dob": "01-01-1991", "name": "Tom Benzamin" }
The address DBRef field here specifies that the referenced address document lies in address_home collection under tutorialspoint database
and has an id of 534009e4d852427820000002.
The following code dynamically looks in the collection specified by $refparameter (address_home in our case) for a document with id as specified by$id parameter
in DBRef.
>var user = db.users.findOne({"name":"Tom Benzamin"}) >var dbRef = user.address >db[dbRef.$ref].findOne({"_id":(dbRef.$id)})
The above code returns the following address document present inaddress_home collection:
{ "_id" : ObjectId("534009e4d852427820000002"), "building" : "22 A, Indiana Apt", "pincode" : 123456, "city" : "Los Angeles", "state" : "California" }
相关文章推荐
- Fast paging with MongoDB
- mongodb中如何创建数据库
- MongoDB聚合整理
- MongoDB 数据模型设计
- Linux下Mongodb安装和启动配置
- DoraCMS 基于Nodejs+express+mongodb 内容管理系统
- mongodb基本指令
- 【mongoDB运维篇②】备份与恢复(导入与导出)
- mongodb(5)-分片集群
- MongoDb(4)
- 定时任务知多少(二)——持久化quartz到Mongodb中
- MongoDB培训
- MongoDB数据库建立连接
- 【mongoDB运维篇①】用户管理
- [置顶] Mongodb性能调优
- MongoDb 聚合报错
- C#操作MongoDB帮助类
- Java MongoDB : Save image example
- Java MongoDB : Save image example
- java mongodb 修改