我的 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# / .NET7 驱动程序翻译 MongoDB 查询。
是的,您的查询应包含
$unwind
和 $group
阶段。
db.collection.aggregate([
{
$unwind: "$categories"
},
{
$group: {
_id: "$categories",
tags: {
$push: {
name: "$tagName",
value: "$tagValue"
}
}
}
},
{
$project: {
_id: 0,
category: "$_id",
tags: 1
}
}
])
对于 MongoDB .NET 驱动程序语法,您应该为展开和投影/结果创建模型。
示例:
public class RootModel
{
public ObjectId Id { get; set; }
public string TagName { get; set; }
public string TagValue { get; set; }
public List<string> Categories { get; set; }
public List<string> OtherField1 { get; set; }
public string OtherField2 { get; set; }
}
public class UnwindRootModel
{
public ObjectId Id { get; set; }
public string TagName { get; set; }
public string TagValue { get; set; }
public string Categories { get; set; }
public List<string> OtherField1 { get; set; }
public string OtherField2 { get; set; }
}
[BsonNoId]
public class ResultModel
{
public string Category { get; set; }
public List<TagModel> Tags { get;set; }
}
[BsonNoId]
public class TagModel
{
public string Name { get; set; }
public string Value { get; set; }
}
在从集合中查询之前,由于文档的字段采用驼峰式大小写,因此您需要通过
[BsonElement]
属性将字段名称指定为驼峰式大小写到类的属性中,或者您应该注册驼峰式大小写包。
var pack = new ConventionPack();
pack.Add(new CamelCaseElementNameConvention());
ConventionRegistry.Register("camel case", pack, t => true);
聚合流畅:
var result = await _collection.Aggregate()
.Unwind<RootModel, UnwindRootModel>(x => x.Categories)
.Group(x => x.Categories,
g => new ResultModel
{
Category = g.Key,
Tags = g.Select(y => new TagModel
{
Name = y.TagName,
Value = y.TagValue
}).ToList()
})
.ToListAsync();
如果您在编写聚合流畅查询时遇到困难,您可以使用 MongoDB Compass 提供原始查询。