大家好,我是考100分的小小码 ,祝大家学习进步,加薪顺利呀。今天说一说mongodb聚合机制_java聚合和关联的区别代码,希望您对编程的造诣更进一步.
db.forex.insert([
{
ccy: "USD",
rate: 6.91,
date: new Date("2018-12-21")
},
{
ccy: "GBP",
rate: 8.72,
date: new Date("2018-08-21")
},
{
ccy: "CNY",
rate: 1.0,
date: new Date("2018-10-21")
}
])
代码100分
用户表数据
代码100分> db.accounts.find().pretty()
{
"_id" : ObjectId("5d80c37349f3060f1212a055"),
"name" : {
"first_name" : "qingquan",
"last_name" : "zeng"
},
"balance" : 100,
"currency" : [
"CNY",
"USD"
]
}
{
"_id" : ObjectId("5d80c37349f3060f1212a056"),
"name" : {
"first_name" : "fengxia",
"last_name" : "yu"
},
"balance" : 200,
"currency" : "GBP"
}
使用lookup来对表进行关联查询
- from 要关联的表
- localField 当前表字段
- foreignField 当前表字段要关联的外表字段
- as 新增字段展示关联的结果
db.accounts.aggregate([
{
$lookup: {
from: "forex",
localField: "currency",
foreignField: "ccy",
as: "forexData"
}
}
])
得出如下结果
代码100分{
"_id" : ObjectId("5d80c37349f3060f1212a055"),
"name" : {
"first_name" : "qingquan",
"last_name" : "zeng"
},
"balance" : 100,
"currency" : [
"CNY",
"USD"
],
"forexData" : [
{
"_id" : ObjectId("5d82226fc404a31cf5199942"),
"ccy" : "USD",
"rate" : 6.91,
"date" : ISODate("2018-12-21T00:00:00Z")
},
{
"_id" : ObjectId("5d82226fc404a31cf5199944"),
"ccy" : "CNY",
"rate" : 1,
"date" : ISODate("2018-10-21T00:00:00Z")
}
]
}
{
"_id" : ObjectId("5d80c37349f3060f1212a056"),
"name" : {
"first_name" : "fengxia",
"last_name" : "yu"
},
"balance" : 200,
"currency" : "GBP",
"forexData" : [
{
"_id" : ObjectId("5d82226fc404a31cf5199943"),
"ccy" : "GBP",
"rate" : 8.72,
"date" : ISODate("2018-08-21T00:00:00Z")
}
]
}
关联修改
将特定日期的外汇汇率写入银行账户文档
# 所有账号的 forexData 匹配的都是 2018-08-21 的记录
# 使用了 pipeline 之后,就不能同时使用 localField 与 foreignField 了
db.accounts.aggregate([
{
$lookup: {
from: "forex",
pipeline: [
{
$match: {
date: new Date("2018-08-21")
}
}
],
as: "forexData"
}
}
])
{
"_id" : ObjectId("5d80c37349f3060f1212a055"),
"name" : {
"first_name" : "qingquan",
"last_name" : "zeng"
},
"balance" : 100,
"currency" : [
"CNY",
"USD"
],
"forexData" : [
{
"_id" : ObjectId("5d82226fc404a31cf5199943"),
"ccy" : "GBP",
"rate" : 8.72,
"date" : ISODate("2018-08-21T00:00:00Z")
}
]
}
{
"_id" : ObjectId("5d80c37349f3060f1212a056"),
"name" : {
"first_name" : "fengxia",
"last_name" : "yu"
},
"balance" : 200,
"currency" : "GBP",
"forexData" : [
{
"_id" : ObjectId("5d82226fc404a31cf5199943"),
"ccy" : "GBP",
"rate" : 8.72,
"date" : ISODate("2018-08-21T00:00:00Z")
}
]
}
将特定日期的外汇汇率写入余额大于100的银行账户文档
# 使用let来区分pipeline用到的字段为本表字段还是外表字段
# 要使用let声明的变量时,需要在pipeline中使用 $expr
db.accounts.aggregate([
{
$lookup: {
from: "forex",
let: {
bal: "$balance"
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: ["$date", new Date("2018-08-21")]
},
{
$gt: ["$$bal", 100]
}
]
}
}
}
],
as: "forexData"
}
}
])
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/9132.html