Mongo将foreignField对象转换为字符串

时间:2019-07-20 19:39:38

标签: node.js mongodb

有很多示例将localField变量从类似的对象转换为字符串。

dbo.collection('exampleCollection').aggregate{[
{
    $lookup: {
          from:'User_List',
          localField:'id',
          foreignField:'_id', //how do I convert the foreignField Object to string?
          as:'whatever'
        }
    }]
}

这些是集合。

enter image description here enter image description here

是否可以将foreignField变量转换为字符串?这部分对我来说至关重要,因为这是我所缺少的查询的唯一部分。 预先谢谢大家!

2 个答案:

答案 0 :(得分:1)

您可以使用以下汇总

dbo.collection("exampleCollection").aggregate([
  { "$lookup": {
    "from": "User_List",
    "let": { "id": "$id" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": [{ "$toString": "$_id" }, "$$id"] }}}
    ],
    "as": "whatever"
  }}
])

答案 1 :(得分:0)

实际上,不是将foreingField转换为字符串,而是将localField转换为字符串,以便您可以将对象之间进行比较。

示例代码如下:

{$lookup:{
     from:'User_List',
     let:{resultObj:{$toObjectId:'$result'}},
     pipeline:
     [{
         $match:{
             $expr:{$eq:['$_id','$$resultObj']}
         }
     }],
     as:'whatever'
  }
}

如果它看起来很脏,我深表歉意。我仍然习惯于mongo以及如何正确缩进。

相关问题