使用mongodb $ lookup与数组

时间:2016-06-03 15:43:05

标签: mongodb lookup

我正在尝试将配置集合的内容与公司集合中的配置数组合并。因此company.configurations是一个数组,其中每个元素都引用了配置集合中的_id。

> db.configurations.find();
{
    "_id" : ObjectId("57518eea52feed9c4f70fc42"),
    "name" : "some_config_flag",
    "area" : "application",
    "default_value" : false
}
{
    "_id" : ObjectId("57518f8f52feed9c4f70fc43"),
    "area" : "application",
    "name" : "some_config_date"
}

> db.companies.find();
{
    "_id" : ObjectId("5751935952feed9c4f70fc45"),
    "name" : "Demo",
    "configurations" : [
        {
            "configuration_id" : ObjectId("57518eea52feed9c4f70fc42"),
            "value" : false
        }
     ]
}
{
    "_id" : ObjectId("57519716fe1cc8d0575bcdfc"),
    "name" : "Acme",
    "configurations" : [
        {
            "configuration_id" : ObjectId("57518eea52feed9c4f70fc42"),
            "value" : true
        },
        {
            "configuration_id" : ObjectId("57518f8f52feed9c4f70fc43"),
            "value" : ISODate("2016-06-30T00:00:00Z")
        }
    ]
}
>

我已尝试使用$ lookup来实现此目的,但查找引用仍为空:

db.companies.aggregate([
{
    $lookup:{
        from:"configurations",
        localField:"_id",
        foreignField: "configuration_id",
        as: "configuration"
    }
 }])

db.companies.aggregate([
{
    $lookup:{
        from:"configurations",
        localField:"_id",
        foreignField: "configurations.configuration_id",
        as: "configuration"
    }
 }])

同时切换localField& foreignField没有帮助。 $ lookup是否支持这种查询,还是作为应用程序代码的一部分解决?

0 个答案:

没有答案