使用 mongodb C# 驱动程序映射投影结果
Map projection result with mongodb C# driver
我需要将集合中的一些文档映射到简化文档。
我可以在 mongo shell:
中获得我需要的东西
db.getCollection('items').aggregate([
{ "$project": {
"Team": "$TeamId",
"Marker": "$Properties.marker.Value"
}}
])
我需要使用 C# 驱动程序(版本 2.3.0)获得相同的结果;我试过了
var aggregation = m_database.GetCollection<BsonDocument>("items").Aggregate();
var projectionDefinition = new BsonDocument("$project", new BsonDocument
{
{ "Team", "$TeamId"},
{ "Marker", "$Properties.marker.Value" }
});
var query = aggregation.Project(projectionDefinition);
var result = await query.ToListAsync();
但我收到以下错误
Command aggregate failed: $expressions are not allowed at the top-level of $project
有人知道这是怎么回事吗?
如果你调用 Project
你的 bson 中已经有 $project
,
所以你只需简化你的 projectionDefinition:
var projectionDefinition = new BsonDocument
{
{ "Team", "$TeamId"},
{ "Marker", "$Properties.marker.Value" }
};
我个人的意见:我会避免使用纯 bson,MongoDB 驱动程序让你有可能使用你的 c# dto 类。
我需要将集合中的一些文档映射到简化文档。 我可以在 mongo shell:
中获得我需要的东西db.getCollection('items').aggregate([
{ "$project": {
"Team": "$TeamId",
"Marker": "$Properties.marker.Value"
}}
])
我需要使用 C# 驱动程序(版本 2.3.0)获得相同的结果;我试过了
var aggregation = m_database.GetCollection<BsonDocument>("items").Aggregate();
var projectionDefinition = new BsonDocument("$project", new BsonDocument
{
{ "Team", "$TeamId"},
{ "Marker", "$Properties.marker.Value" }
});
var query = aggregation.Project(projectionDefinition);
var result = await query.ToListAsync();
但我收到以下错误
Command aggregate failed: $expressions are not allowed at the top-level of $project
有人知道这是怎么回事吗?
如果你调用 Project
你的 bson 中已经有 $project
,
所以你只需简化你的 projectionDefinition:
var projectionDefinition = new BsonDocument
{
{ "Team", "$TeamId"},
{ "Marker", "$Properties.marker.Value" }
};
我个人的意见:我会避免使用纯 bson,MongoDB 驱动程序让你有可能使用你的 c# dto 类。