下面的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}
}}
]
} )
我正在尝试将上述查询转换为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);
但是出现错误无法从BsonType'Document'反序列化'Int32'。
Id是集合中的主键
public int ID {get;组; }
请告知如何实现此目标。
(Robo 3T 1.2.1)(MongoDB.Driver 2.4.4)
答案 0 :(得分:0)
您正试图通过为“ _id”创建BsonDocument将BsonDocument反序列化为“ Int32”。您只需要这样做:
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
}
}
}
}
}
};