$ lookup不适用于以$开头的字段

时间:2019-05-15 11:45:57

标签: mongodb

b.getCollection('actions').aggregate([
      { $lookup : {
           from: "companies",
           localField: "company.$id",
           foreignField: "companies:_id",
           as: "companyId"
           }
      }
])

错误消息:fieldpath field names cannot start with $

我无法重命名该字段,它是一个生产站点,并且如果无法执行简单的JOIN,我将回到SQL。

b.getCollection('actions').aggregate([
     { $lookup : {
           from: "companies",
           localField: "company.$id",
           foreignField: "companies:_id",
           as: "companyId"
            }
     }
])

2 个答案:

答案 0 :(得分:0)

您的“ JOINT”中有语法错误,看起来应该是这样

b.getCollection('actions').aggregate([
     {
        $lookup : {
           from: "companies",
           localField: "_id",
           foreignField: "companies._id",
           as: "companyId"
          }
     }
])

-我假设这就是您的模式外观,除非您共享它,否则无法真正知道。

答案 1 :(得分:0)

DBrefs 将具有以'$'开头的字段,因此我们无法使用直接 在DBrefs上 $ lookup

使用$objectToArray,可以使用$ lookup (版本3.4.4 及更高版本支持$ objectToArray)

db.getCollection('actions').aggregate([
{
     $project: 
     {
       companiesArray: { $objectToArray: "$company" }
     }
},
{
     $unwind: "$companiesArray"
},
{
     $match:  {"companiesArray.k" :"$id"}
},

{ $lookup : {
       from: "companies",
       localField: "companiesArray.v",
       foreignField: "_id",
       as: "companyId"
       }
}
])