我是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
是可变的答案 0 :(得分:1)
如何在聚合管道中没有硬编码“A”,“B”,“C”的情况下获得它。我的键值对将变得更大,并且对于给定的id
是可变的
您可以利用新的聚合运算符$arrayToObject
(SERVER-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灵活架构并重新考虑您的文档模型。