[英]C# Mongo Driver error: Cannot deserialize a 'Int32' from BsonType 'Document'
Following MongoDB query run fine on Robo3T 1.2 and return correct 'count'. 以下MongoDB查询在Robo3T 1.2上运行良好,并返回正确的“计数”。
db.runCommand( {
aggregate: "User",
pipeline: [
{$unwind: '$UserSubscriptions'},
{$group: {
_id: '$_id',
codes: {$addToSet: '$UserSubscriptions.Subscription.Publication'}
}},
{$unwind: '$codes'},
{$group: {
_id: '$codes',
count: {$sum: 1}
}}
]
} )
I m trying to convert above query to C# MongoDriver query like this 我正在尝试将上述查询转换为C#MongoDriver查询
var unwind = new BsonDocument { { "$unwind", "$UserSubscriptions" } };
var group1 = new BsonDocument
{
{ "$group",
new BsonDocument
{
{ "_id", new BsonDocument
{
{
"Id","$_id"
}
}
},
{
"codes", new BsonDocument
{
{
"$addToSet","$UserSubscriptions.Subscription.Publication.Code"
}
}
}
}
}
};
var unwindCode = new BsonDocument { { "$unwind", "$codes" } };
var group2 = new BsonDocument
{
{ "$group",
new BsonDocument
{
{ "_id", new BsonDocument
{
{
"Id","$codes"
}
}
},
{
"codes", new BsonDocument
{
{
"$sum",1
}
}
}
}
}
};
var pipeline = new[] { unwind, group1 , unwindCode , group2 };
var result = coll.Aggregate<T>(pipeline);
But getting error Cannot deserialize a 'Int32' from BsonType 'Document'. 但是出现错误无法从BsonType'Document'反序列化'Int32'。
Id is a primary key in collection ID是集合中的主键
public int Id { get; public int ID {get; set;
组; }
}
Please advise how to achieve this. 请告知如何实现此目标。
(Robo 3T 1.2.1) (MongoDB.Driver 2.4.4) (机器人3T 1.2.1)(MongoDB.Driver 2.4.4)
You are trying to deserialize a BsonDocument to 'Int32' by creating a BsonDocument for "_id". 您正在尝试通过为“ _id”创建BsonDocument将BsonDocument反序列化为“ Int32”。 You just need to do this:
您只需要这样做:
var group1 = new BsonDocument
{
{
"$group", new BsonDocument
{
{
"_id", "$_id"
},
{
"codes", new BsonDocument
{
{
"$addToSet", "$UserSubscriptions.Subscription.Publication.Code"
}
}
}
}
}
};
var group2 = new BsonDocument
{
{
"$group", new BsonDocument
{
{
"_id", "$codes"
},
{
"count", new BsonDocument
{
{
"$sum", 1
}
}
}
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.