我刚接触MongoDB,不了解聚合管道。我有一个名为Portfolio的集合,下面是一个示例文档:
{
"_id" : "fjkhjkdshjkhkdsgfsadhfghgdsa",
"Name" : "Alex's Portfolio",
"Stocks" : [
{
"StockId" : NumberInt(5454125454796),
"Quantity" : NumberInt(30),
"InvestedValue" : "4124"
},
{
"StockId" : NumberInt(5745454554541),
"Quantity" : NumberInt(6),
"InvestedValue" : "3048"
}
],
"MutualFunds" : [
{
"MutualFundId" : NumberInt(472546545646564),
"Quantity" : "12",
"InvestedValue" : "5233"
}
]
}
我有两个主集合,名为股票:
[{
"_id" : "d5043755-ff4d-47da-bbff-df838a79df3b",
"StockId" : NumberInt(5454125454796),
"Name" : "AB Industries Ltd.",
"LastPrice" : "5.70",
"LastPriceChange" : "0.27"
},
{
"_id" : "49224732-f380-4e6f-a933-6fdb5b42107f",
"StockId" : NumberInt(5745454554541),
"Name" : "AB Industries 2 Ltd.",
"LastPrice" : "5.70",
"LastPriceChange" : "0.27"
}]
&共同基金:
[{
"_id" : "3d8a4baa-34e6-4e5b-b782-ec4eda213fc9",
"MfId" : NumberInt(472546545646564),
"Name" : "AB Industries Bond",
"LastNAV" : "1036.747",
"LastNAVChange" : "0.3298",
}]
我曾尝试使用这个作为参考,但没有工作在.NET核心6与MongoDB驱动程序。
现在,我如何通过聚合管道实现下面给定的JSON:
{
"Name": "Alex's Portfolio",
"Securities": [
{
"StockId": 5454125454796,
"Name": "AB Industries Ltd.",
"LastPrice": 5.7,
"LastPriceChange": 0.27,
"Quantity": 30,
"InvestedValue": 4124
},
{
"StockId": 5745454554541,
"Name": "AB Industries 2 Ltd.",
"LastPrice": 5.7,
"LastPriceChange": 0.27,
"Quantity": 6,
"InvestedValue": 3048
}
],
"Mfs": [
{
"MfId": 472546545646564,
"Name": "AB Industries Bond",
"LastNAV": 1036.747,
"LastNAVChange": 0.3298,
"Quantity": 12,
"InvestedValue": 5233
}
]
}
1条答案
按热度按时间zf2sa74q1#
这似乎是一个复杂而冗长的查询。
$lookup
-加入“证券”集合并返回Securities
数组。$lookup
-加入“MutualFunds”集合并返回Mfs
数组。$set
-3.1.设置
Securities
字段,通过将每个对象与Stocks
数组中的对象合并来执行Map。3.2.将
Mfs
字段设置为通过将每个对象与MutualFunds
数组中的对象合并来执行Map。$unset
-删除不需要的字段。Demo @ Mongo Playground
使用MongoDB Compass,它允许export the aggregation pipeline into a specific language。您可以在C#中使用
BsonDocument
来处理查询。1.构造输出模型类。
1.执行聚合管道。