MongoDb关键值的Pivot

时间:2017-04-04 15:24:25

标签: mongodb pivot aggregation-framework

我是MongoDB中的新蜜蜂,我收集了如下所示的键值对。 input collection

{"restaurantid" : NumberInt("1"), 
"Properties" : [ 
  { "Key" : "A", "Value" : NumberInt("25") }, 
  { "Key" : "B", "Value" : "StringValue" }, 
  { "Key" : "C", "Value" : ISODate("2017-02-09") } 
] }

我看结果集为 Output Collection

{ "restaurantid" : NumberInt("1"), 
  "A" : NumberInt("25"), 
  "B" : "StringValue", 
  "C" : ISODate("2017-02-09") 
}

如何在聚合管道中没有硬编码“A”,“B”,“C”的情况下获得它。我的键值对将变得更大,并且对于给定的id

是可变的

1 个答案:

答案 0 :(得分:1)

  

如何在聚合管道中没有硬编码“A”,“B”,“C”的情况下获得它。我的键值对将变得更大,并且对于给定的id

是可变的

您可以利用新的聚合运算符$arrayToObjectSERVER-18794)来调整MongoDB密钥。此运算符目前在MongoDB v3.4.4 +

中可用

例如,您可以重构架构:

{
  "restaurantid" : NumberInt("1"),
  "Properties" : [
    { "k" : "A", "v" : NumberInt("25") },
    { "k" : "B", "v" : "StringValue" },
    { "k" : "C", "v" : ISODate("2017-02-09") }
  ]
}

然后您可以使用下面的示例aggregation pipeline

db.collection.aggregate(
[
    {$project:{"tmp":{$arrayToObject:"$Properties"}, "restaurantid":"$resturantid"}}, 
    {$addFields:{"tmp.restaurantid":"$restaurantid"}}, 
    {$replaceRoot:{newRoot:"$tmp"}}
]);

另请参阅$replaceRoot$addFields。根据您的使用案例,您还可以利用MongoDB灵活架构并重新考虑您的文档模型。