在Ruby on Rails项目中,我有一个名为MongoDB的事件集合:
{
_id: 1, title: Event-1, timestamp: 1567687654, data: {"a": 23,"b": 40}, machine_key: "key1",
_id: 2, title: Event-2, timestamp: 1567687656, data: {"a": 11,"b": 49}, machine_key: "key2",
_id: 3, title: Event-3, timestamp: 1567687658, data: {"a": 10,"b": 50}, machine_key: "key2",
...
}有一个外部哈希图(不是MongoDB集合)具有以下结构-
machine_map = {"key1" : {"code": "M1", "type": "Type A"}, "key2" : {"code": "M2", "type": "Type B"},...... }我想在集合上使用聚合管道来产生这样的结果:
db.Events.aggregate([
{ $match: { title: "Event-1" } },
{ $project: { title: 1, machine_key: 1, machine_data: machine_map["$machine_key"] } }
])如何使用machine_key字段从外部哈希图machine_map获取数据?
发布于 2020-07-17 15:51:00
您必须对对象进行“迭代”,并使用Mongo操作符来匹配值。有几种不同的方法可以做到这一点,下面是一个例子:
db.Events.aggregate([
{
$match: {
title: "Event-1"
}
},
{
$project: {
title: 1,
machine_key: 1,
machine_data: {
$arrayElmAt: [
{
$reduce: {
input: {
$filter: {
input: {$objectToArray: machine_map},
as: "m",
cond: {$eq: ["$$m.k", "$machine_key"]}
}
},
initialValue: {},
in: "$$this.v"
}
},
0
]
}
}
}
]);发布于 2020-07-17 17:22:10
您可以使用基于该哈希映射的$switch表达式。使用ruby构建交换机,并使用管道提交它。
{$project: {
machine_data: {
$switch: {
branches: [
{case: {$eq:["machine_key","key1"]}, then: {"code": "M1", "type": "Type A"}},
{case: {$eq:["machine_key","key2"]}, then: {"code": "M2", "type": "Type B"}},
...
]
}
}
}}https://stackoverflow.com/questions/62949378
复制相似问题