How to convert ObjectID to string in $ lookup (aggregate)

I have two collections, article and comments, articleId

in the comments is the foreign key _id

in the article.

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

      

but it does not work, because _id

in the article - it's ObjectID

a articleId

- it's a string.

+5


source to share


2 answers


You can achieve this using aggregation which simply converts the string id to mongoose objectId $toObjectId

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 aggregation $toString

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

      

0


source


You can directly use $toString

on the field _id

:

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

      



But MongoDB 3.6

does not support type conversion inside the aggregation pipeline. So $toString

and $convert

will only work with MongoDB 4.0

.

0


source







All Articles