MongoDB 在 _id 字段上加入从 String 到 ObjectId 的聚合 $lookup

MongoDB Join on _id field from String to ObjectId aggregate $lookup

我有两个collection。

客户:

{
   "_id" : ObjectId("584aac38686860d502929b8b"),
   "name" : "user",
   "email" : "user@gmail.com"
}

帖子:

{
   "_id" : ObjectId("584aaca6686860d502929b8d"),
   "title" : "Post",
   "description":"description",
   "user_id" : "584aac38686860d502929b8b"  
}

我想加入这个collection基于user_id(来自postscollection)-_id(在customerscollection ).

我尝试了以下查询:

dbo.collection('customers').aggregate([
        {
            $lookup:
                {
                    from: 'posts',
                    localField: 'user_id',
                    foreignField: '_id',
                    as: 'posts'
                }
        }
    ])

但它不起作用。

我得到的输出:

{
    "_id": "584aac38686860d502929b8b",
    "name": "user",
    "email": "user@gmail.com",
    "posts": []
}

来自附加的 posts 集合,user_id 是一个字符串而不是 ObjectId

要进行比较,您必须先将 user_id 转换为 ObjectId

db.customers.aggregate([
  {
    $lookup: {
      from: "posts",
      let: {
        customerId: "$_id"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [
                {
                  "$toObjectId": "$user_id"
                },
                "$$customerId"
              ]
            }
          }
        }
      ],
      as: "posts"
    }
  }
])

Sample Mongo Playground


注意:根据您现有的 $lookup,您已反转 localFieldforeignField

Equality Match with a Single Join Condition

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}