我在MongoDB 6.0中构建了如下文档:
[
{
"_id" : ObjectId("6555a7d7c2d9de74abb09de8"),
"tagName" : "tag1",
"tagValue" : "value1",
"categories" : [
"Category-1"
],
"otherField1" : [],
"otherField2" : "something-else-1"
},
{
"_id" : ObjectId("6555a865c2d9de74abb09de9"),
"tagName" : "tag2",
"tagValue" : "value2",
"categories" : [
"Category-1",
"Category-2"
],
"otherField1" : [],
"otherField2" : "something-else-2"
},
{
"_id" : ObjectId("6555c652c2d9de74abb09df2"),
"tagName" : "tag3",
"tagValue" : "value3",
"categories" : [
"Category-2",
"Category-3",
],
"otherField1" : [],
"otherField2" : "something-else-3"
}
]
字符串
我想把它们转换成下面的结构。
[
{
"category" : "Category-1",
"tags" : [
{
"name" : "tag1",
"value" : "value1"
},
{
"name" : "tag2",
"value" : "value2"
}
]
},
{
"category" : "Category-2",
"tags" : [
{
"name" : "tag2",
"value" : "value2"
},
{
"name" : "tag3",
"value" : "value3"
}
]
},
{
"category" : "Category-3",
"tags" : [
{
"name" : "tag3",
"value" : "value3"
}
]
}
]
型
我使用了$unwind
和$group
运算符,但无法得到最终结果。感谢任何帮助。
PS:最后,我必须使用C#/.NET 7驱动程序翻译MongoDB查询。
1条答案
按热度按时间6ioyuze21#
是的,您的查询应该包含
$unwind
和$group
阶段。字符串
对于MongoDB .NET Driver语法,您应该为展开和投影/结果创建模型。
范例:
型
在从集合中查询之前,由于您的文档的字段是 Camel 大小写,因此您需要通过
[BsonElement]
属性将字段名称指定为 Camel 大小写到类的属性中,或者您应该注册 Camel 大小写包。型
使用Aggregate Fluent:
型
x1c 0d1x的数据
如果在编写聚合流畅查询时遇到困难,可以使用MongoDB Compass提供原始查询。
**更新:**如帖子所有者所述,删除重复的标签,将
.Distinct()
应用于Aggregate Fluent/LINQ中的Tags
列表。