1.查看数据库
show dbs
2.创建runoob数据库
use runoob
3.查看runoob中集合
show collections
4.创建地址集合(address_home,address_office)
db.createCollection("address_home")
db.createCollection("address_office")
5.查看创建的集合
show collections
6.分别向家庭(address_home)地址集合和办公(address_office)地址集合添加数据
db.address_home.insertOne({
'name':'home address',
'province':'jiangsu',
'city':'xuzhou'
})
查看address_home数据
db.address_home.find().pretty()
db.address_office.insertOne({
'name':'office address',
'province':'jiangsu',
'city':'nanjing'
})
查看address_office数据
db.address_office.find().pretty()
7.创建用户集合(users)
db.createCollection("users")
8.查看创建集合
show collections
9.向users集合添加数据
db.users.insertOne({
"name":"suyanzhu",
"address":{
"$ref":"address_home",
"$id":ObjectId("5bd2b70fabb45c7371f36eda")
},
"age":18
})
查看集合中的数据
db.users.find().pretty()
10.查看用户具体的地址信息
var user = db.users.findOne({"name":"suyanzhu"})
user
var dbRef = user.address
dbRef
var collName = dbRef.$ref
collName
var id = dbRef.$id
id
db[collName].findOne({"_id":id})