Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert ObjectID to String in $lookup (aggregation)

I have two collections, article and comments, the articleId in comments is a foreign key of _id in article.

db.collection('article').aggregate([
  {
    $lookup: {
      from: "comments",
      localField: "_id",
      foreignField: "articleId",
      as: "comments"
    }
  },
  ...
])

but it doesn't work, because _id in article is an ObjectID and articleId is a string.

like image 466
cityvoice Avatar asked Jun 03 '17 14:06

cityvoice


1 Answers

You can achieve this using $addFields and $toObjectId aggregations which simply converts string id to mongo objectId

db.collection('article').aggregate([
  { "$lookup": {
    "from": "comments",
    "let": { "article_Id": "$_id" },
    "pipeline": [
      { "$addFields": { "articleId": { "$toObjectId": "$articleId" }}},
      { "$match": { "$expr": { "$eq": [ "$articleId", "$$article_Id" ] } } }
    ],
    "as": "comments"
  }}
])

Or using $toString aggregation

db.collection('article').aggregate([
  { "$addFields": { "article_id": { "$toString": "$_id" }}},
  { "$lookup": {
    "from": "comments",
    "localField": "article_id",
    "foreignField": "articleId",
    "as": "comments"
  }}
])
like image 98
Ashh Avatar answered Oct 21 '22 18:10

Ashh