[英]How to join collections by id with MongoDb C# Driver
我正在尝试加入Id
两个收藏。 尽管我可以看到数据库中的行,但查询结果为空。
我有两个集合: userGames
和games
这是我加入收藏集的代码:
var userGamesQuery = userGames.AsQueryable()
.Where(x => x.UserId == userId);
var query = from userGame in userGamesQuery
join game in games.AsQueryable() on userGame.GameId equals game.Id
select game;
第一部分返回13个元素,但是第二部分不返回任何内容。 我认为该行userGame.GameId equals game.Id
有一些问题。 试图在userGame.GameId
和game.Id
上都使用ObjectId.Parse()
,但是没有运气。
这是我的模特儿
游戏类别:
public class Game
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
}
UserGames:
public class UserGames
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string UserId { get; set; }
public string GameId { get; set; }
}
问题是,当您运行“ join”时,它将尝试在数据库侧的两个字段上运行相等比较。 要考虑两个值相等,MongoDB检查第一个和十个值的类型。 由于GameId
的类型为string
且Id
以BsonId
形式存储,因此这些集合之间将没有匹配项。
解决此问题的最简单方法是将您的班级更改为:
public class UserGames
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string UserId { get; set; }
[BsonRepresentation(BsonType.ObjectId)]
public string GameId { get; set; }
}
并在数据库上运行脚本以转换现有数据。 可能是这样的:
db.UserGames.aggregate([
{ $addFields: { GameId: { $toObjectId: "$GameId" } } },
{ $out: "UserGames" }
])
您也可以尝试在聚合中直接使用$ toObjectId或$ toString转换类型,但是没有使用强类型驱动程序API的简便方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.