mongodb – 如何在$lookup(聚合)中將ObjectID轉換為String


我有兩個集合,文章和評論,評論中的文章是文章中_id的外鍵. 
db.collection('article').aggregate(
          [
            {
              $lookup:
                {
                  from: "comments",
                  localField: "_id",
                  foreignField: "articleId",
                  as: "comments"
                }
            },
          ...

 

它不起作用,因為文章中的_id是一個ObjectID而articleId是字符串,那怎么辦?

 
您可以使用  $toObjectId聚合實現此目的,該聚合僅將字符串ID轉換為mongoose 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"
  }}
])

 

或者使用$toString聚合

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM