如何使用两个外键在mongoDB中进行查找?

时间:2016-11-24 10:25:40

标签: mongodb lookup

三个产品系列ProductDescription,这样的语言:

> db.Language.find();
{
    "_id" : ObjectId("1234..."),
    "isoCc" : "EN"
}
{
    "_id" : ObjectId("5678..."),
    "isoCc" : "DE"
}

> db.Product.find();
{
    "_id" : ObjectId("3eff..."),
    "sku" : "123456",
    "title" : "Some Product Title"
}

> db.ProductDescription.find();
{
    "_id" : ObjectId("44ad..."),
    "ofProduct" : ObjectId("3eff..."),
    "ofLanguage" : ObjectId("1234..."),
    "shortDescription" : "English description"
}
{
    "_id" : ObjectId("f5aa..."),
    "ofProduct" : ObjectId("3eff..."),
    "ofLanguage" : ObjectId("5678..."),
    "shortDescription" : "German description"
}

如果我像这样查找ProductDescription

db.Product.aggregate([
  {
    $lookup:
      {
        from: "ProductDescription",
        localField: "_id",
        foreignField: "ofProduct",
        as: "description"
      }
  }
])

我得到了ProductDescription的两个部分。

那么我怎么能过滤描述应该是什么语言呢?

1 个答案:

答案 0 :(得分:1)

如果您还要查找描述语言,则需要对description.ofLanguage

使用另一个查找
db.Product.aggregate([
  {
    $lookup:
      {
        from: "ProductDescription",
        localField: "_id",
        foreignField: "ofProduct",
        as: "description"
      }
  },
  {
    $lookup:
      {
        from: "Language",
        localField: "description.ofLanguage",
        foreignField: "_id",
        as: "language"
      }
  }
])