简体   繁体   English

使用 C# Driver 通过 MongoDB 中 ID-to-ID 集合中的匹配查询集合

[英]Querying a collection via a match in an ID-to-ID collection in MongoDB using C# Driver

I have the following collection document types:我有以下收集文档类型:

Car
{
   Id
   Make
   Model
}

and

UserCar
{
   UserId
   CarId   (references Car.Id)
}

I'm having trouble finding the correct query using MongoDB C# Driver to:我无法使用 MongoDB C# 驱动程序找到正确的查询:

Get all Cars where UserId = x获取 UserId = x 的所有汽车

This is a very simple query in SQL, so I'm quite frustrated that this is proving so difficult with their SDK (for me, at least).这是 SQL 中的一个非常简单的查询,所以我很沮丧,因为他们的 SDK(至少对我而言)被证明如此困难。 It's the ID-to-ID collection containing the filter that seems to be the issue.它是包含过滤器的 ID 到 ID 集合,这似乎是问题所在。 So, starting with:所以,从:

var db = MongoUtil.GetDb();
var cars = db.GetCollection<Car>("Cars");
var userCars = db.GetCollection<UserCar>("UserCars");

List<Car> carsJoined = ??? where UserId = 1234

Thanks for the help.谢谢您的帮助。

Work with MongoDB .NET Driver .Aggregate() (Although the query below looks a bit complex).使用 MongoDB .NET Driver .Aggregate() (尽管下面的查询看起来有点复杂)。

var result = cars
    .Aggregate()
    .Lookup<UserCar, BsonDocument>(
        "UserCars", 
        "Id", 
        "CarId",
        "userCars")
    .Match(Builders<BsonDocument>.Filter
        .ElemMatch<BsonValue>("userCars", new BsonDocument("UserId", 1234)))
    .Project<masterDocument>(Builders<BsonDocument>.Projection
        .Exclude("userCars"))
    .ToList();

This is equivalent to the aggregate query这相当于聚合查询

db.cars.aggregate([
  {
    $lookup: { 
        from: "UserCars",
        localField: "Id"
        foreignField: "CarId",
        as: "userCars"
    }
  },
  {
    $match: {
      "userCars": {
        $elemMatch: {
          "UserId": 1234
        }
      }
    }
  },
  {
    $project: {
      userCars: 0,
      // Other fields: 1
    }
  }
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM