【mongoDB】 学习(三)java + mongodb 多表联合查询
关键字
mongoDB、Java、$lookup、 $project、 $match 等
1、先介绍这次使用的 mongoDB 内的方法以及使用方式(Robo 3T 1.3.1)
mongoDB 官网
https://docs.mongodb.com/manual/reference/operator/aggregation/project/index.html
(1)$lookup
类似SQL server里面的 join
"$lookup": {
"from": "users",//关联目标表名
"localField": "human",//外键
"foreignField": "humanSerialNumber", //目标表明内连接字名
"as": "huamn"//别名
}
(2)$project
类似SQL server里面 select 后面的内容
"$project" : {
"deviceID" :1,//1=显示字段
"humanLoc":1,
"human":"$human",//引入列表
"time":1,
"checkFor":"$devices.area",//重命名列 -表devices下的area 列 (类似sql 里面的as)
}
(3)$match
类似SQL server里面where 后面内容
"$match":{
"origin":"QA",//eq
"bind":{
"$regex":"12972247"}//like
}
(4)$split
字符串切割生成字符数组
{
"$split": ["$bind", "0000000000"] }
(5)$cond
{
"$cond":{
"if":{
"$gte": [ {
"$size":{
"$split": ["$bind", "0000000000"] }}
, 2
]
}
,"then":1
,"else":0
}
}
(6)$arrayElemAt
取列表元素
{
"$arrayElemAt": ["$devices",0]}
2、表bindings、users、devices 三表连表查询
(1)表 bindings–二维码绑定记录表
{
"_id" : ObjectId("5c99d700d360a612e21cccba"),
"qrcode" : "66E88CFEFB964D074290160E2F",
"bind" : "000000000010126460",
"device_info" : "X888D77S6||10126460",
"device_name" : "电动车:0.4t",
"detail" : "设备号: 10126460\n序列号: X888D77S6\n设备类型:CS0001 电动车:1.4t\n送达方客户名: 服务组001\n设备状态: 在客户处 [CUST]",
"human" : "82306690787299121764776791679022450814",
"humanLoc" : "121.610741,31.185281,上海市浦东新区张江高科技园区,上海市浦东新区张江高科技园区,上海市浦东新区张江高科技园区",
"origin" : "QA",
"timestamp" : "1553585920323",
"area_code" : "6053"
}
(2)表 devices–设备表
{
"_id" : ObjectId("5e96a93749b0833d2ad1b211"),
"bindingSerial" : "[X888D77S6] [11313212]",
"origin" : "QA",
"deviceID" : "11313212",
"bindContent" : [
{
"name" : "电动车:0.4t",
"bindFlag" : "11313212",
"bindValues" : [
{
"fieldName" : "设备号",
"fieldValue" : "11313212"
},
{
"fieldName" : "序列号",
"fieldValue" : "G74104-001"
},
{
"fieldName" : "设备类型",
"fieldValue" : "CS0040"
},
{
"fieldName" : "设备状态",
"fieldValue" : "在客户处 [CUST]"
},
{
"fieldName" : "销售组",
"fieldValue" : "CTZ"
},
{
"fieldName" : "设备属性",
"fieldValue" : "R"
}
]
}
],
"area" :