文档之间的关系-------------------------mongodb

Mongodb中处理文档之间的关系:

三种关系:
一对一

一对多

多对多

 

 ###一对一:

 

> db.wifeandhusband.insert({name:"黄蓉",husband:{name:"郭靖"}})
WriteResult({ "nInserted" : 1 })
> db.a.find().count()
20000
> db.wifeandhusband.find();
{ "_id" : ObjectId("656d8addb6da6d16e3a57044"), "name" : "黄蓉", "husband" : { "name" : "郭靖" } }
>

db.wifeandhusband.insert({name:"潘金莲",husband:{name:"武大"}})

> db.wifeandhusband.find();
{ "_id" : ObjectId("656d8addb6da6d16e3a57044"), "name" : "黄蓉", "husband" : { "name" : "郭靖" } }
{ "_id" : ObjectId("656d8b66b6da6d16e3a57045"), "name" : "潘金莲", "husband" : { "name" : "武大" } }
 
 
 
###一对多

 

 ###插入多条数据:一对大括号为一个数据,

> db.users.insert([{username:'aaa'},{username:'bbb'}])
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
> db.users.find();
{ "_id" : ObjectId("656d8cf5b6da6d16e3a57046"), "username" : "aaa" }
{ "_id" : ObjectId("656d8cf5b6da6d16e3a57047"), "username" : "bbb" }
>
##使用用户id来指明”那些订单“是哪个用户来买的,收购或者售卖的:
db.order.insert({list:["苹果","香蕉","橘子"],user_id:ObjectId("656d8cf5b6da6d16e3a57047")})

 db.order.insert({list:["西瓜","香蕉"],user_id:ObjectId("656d8cf5b6da6d16e3a57047")})

  db.order.insert({list:["牛肉","漫画"],user_id:ObjectId("656d8cf5b6da6d16e3a57046")})

 ##查找订单:

#设置用户id的变量

> var user_id = db.users.findOne({username:"aaa"})._id
> db.order.find(user_id:user_id)
SyntaxError: missing ) after argument list :
@(shell):1:21
> db.order.find({user_id:user_id})
{ "_id" : ObjectId("656d9107b6da6d16e3a5704a"), "list" : [ "牛肉", "漫画" ], "user_id" : ObjectId("656d8cf5b6da6d16e3a57046") }
再查bbb的订单有多少:

 

 

###多对多

 

> db.teachers.insert([{name:"洪七公"},{name:"黄药师"},{name:"龟仙人"}]);
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 3,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
> db.teachers.find();
{ "_id" : ObjectId("656d9420b6da6d16e3a5704c"), "name" : "洪七公" }
{ "_id" : ObjectId("656d9420b6da6d16e3a5704d"), "name" : "黄药师" }
{ "_id" : ObjectId("656d9420b6da6d16e3a5704e"), "name" : "龟仙人" }
> db.student.insert({name:"郭靖",teac_id:[ObjectId("656d9420b6da6d16e3a5704c"),ObjectId("656d9420b6da6d16e3a5704d")]});
WriteResult({ "nInserted" : 1 })
> db.student.find();
{ "_id" : ObjectId("656d96232c5120002a059cf5"), "name" : "郭靖", "teac_id" : [ ObjectId("656d9420b6da6d16e3a5704c"), ObjectId("656d9420b6da6d16e3a5704d") ] }
>
 
db.student.insert({name:"孙悟空",teac_id:[ObjectId("656d9420b6da6d16e3a5704e"),ObjectId("656d9420b6da6d16e3a5704d")]});

 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 

posted @ 2023-12-04 16:12  往事已成昨天  阅读(5)  评论(0编辑  收藏  举报