我在查询两个集合并将结果组合成另一个集合时遇到问题。
Collection1:
{
"ResourceCost" : 0.0032258065,
"ResourceId" : "i-08c35f123eea43f30",
"Unit" : "USD",
"billdate" : ISODate("2017-12-01T16:30:00.000Z")
}
收集2:
{
"resource_id" : "i-08c35f123eea43f30",
"Timestamp" : ISODate("2017-12-01T18:30:00.000Z"),
"Avg" : 0.0,
"total" : 0.0,
"sample_cnt" : 1440.0,
"max" : 0.0,
"min" : 0.0
}
我需要使用集合2数据更新集合1。所以最后我期待收集1数据如下
同时检查字段和资源ID。更新数据
收集1:
{
"ResourceCost" : 0.0032258065,
"ResourceId" : "i-08c35f123eea43f30",
"Unit" : "USD",
"billdate" : ISODate("2017-12-01T16:30:00.000Z")
"Avg" : 0.0,
"total" : 0.0,
"sample_cnt" : 1440.0,
"max" : 0.0,
"min" : 0.0
}
答案 0 :(得分:0)
我希望这有帮助,
db.col1.aggregate([
{
$lookup:{
from:"col2",
localField:"ResourceId",
foreignField:"resource_id",
as:"result"
}
},{
$unwind:"$result"
},{
$project:{
"ResourceCost":"$ResourceCost",
"ResourceId":"$ResourceId",
"Unit":"$Unit",
"billdate":"$billdate",
"_id":0,
"avg":"$result.Avg",
"total":"$result.total",
"sample_cnt":"$result.sample_cnt",
"max":"$result.max",
"min":"$result.min"
}
}
])
答案 1 :(得分:0)
在mongodb 3.4中你可以使用这个
db.col1.aggregate([
{
$lookup:{
from:"col2",
localField:"ResourceId",
foreignField:"resource_id",
as:"result"
}
}, {
$replaceRoot: {
newRoot: {
$mergeObjects: [ { $arrayElemAt: [ "$result", 0 ] }, "$$ROOT" ]
}
}
},{
$project: { result: 0 }
}])