好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

mongodb – 如何在$lookup(聚合)中将ObjectID转换为String

"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" 
  }}
]) 

 

mongodb – 如何在$lookup(聚合)中将ObjectID转换为String

标签:let   tostring   cal   div   exp   split   实现   转换   文章   

查看更多关于mongodb – 如何在$lookup(聚合)中将ObjectID转换为String的详细内容...

  阅读:31次