如何MongoDB中对数组进行$lookup连表,将连接获得的数据放入添加到数组

我将二级+评论放入一级评论的comment字段中,前端渲染比较方便。

简化版

    "_id" : ObjectId("624a5b8db5dbe4270038527c"),

"thumbsUp" : [ ],

"cover" : "\\uploads\\1646753148474.jpg",

"articleId" : "622c6a8dd48a854b6c9c5f58",

"userId" : "61f53a222c6dd92ac0881f5e",

"comment" : [

{

"articleId" : "622c6a8dd48a854b6c9c5f58",

"commentId" : "624a5b8db5dbe4270038527c",

"parentId" : "61f53a222c6dd92ac0881f5e",

"userId" : "620fbf1e0c1b451028758e03",

"value" : "<p>回复你哦</p>\n",

},

{

"articleId" : "622c6a8dd48a854b6c9c5f58",

"commentId" : "624a5b8db5dbe4270038527c",

"parentId" : "61f53a222c6dd92ac0881f5e",

"parentName" : "大聪明",

"userId" : "61f53a222c6dd92ac0881f5e",

"value" : "<p>对话1</p>\n",

},

我通过$lookup可以获取每一已连接用户表的数据
但并不是我想要的数据

db.article.aggregate([

{

"$project":

{

"userId":

{

"$convert": {

"input": "$userId",

"to": "objectId"

}

},

'title': 1,

'content': 1,

'author': 1,

'type': 1,

'tag': 1,

'username': 1,

'publishDate': 1,

'comment': 1,

'cover': 1,

},

}, {

$lookup: {

from: 'user',

localField: 'userId',

foreignField: '_id',

as: 'user'

}

}

])

如何MongoDB中对数组进行$lookup连表,将连接获得的数据放入添加到数组

我希望得到这种数据

  "_id" : ObjectId("624a5b8db5dbe4270038527c"),

"thumbsUp" : [ ],

"cover" : "\\uploads\\1646753148474.jpg",

"articleId" : "622c6a8dd48a854b6c9c5f58",

"userId" : "61f53a222c6dd92ac0881f5e",

"comment" : [

{

"articleId" : "622c6a8dd48a854b6c9c5f58",

"commentId" : "624a5b8db5dbe4270038527c",

"parentId" : "61f53a222c6dd92ac0881f5e",

"userId" : "620fbf1e0c1b451028758e03",

"value" : "<p>回复你哦</p>\n",

//连接用户表

"username":"123",

"cover":'1.jpg'

},

{

"articleId" : "622c6a8dd48a854b6c9c5f58",

"commentId" : "624a5b8db5dbe4270038527c",

"parentId" : "61f53a222c6dd92ac0881f5e",

"parentName" : "大聪明",

"userId" : "61f53a222c6dd92ac0881f5e",

"value" : "<p>对话1</p>\n",

//连接用户表

"username":"223",

"cover":'2.jpg'

},

请教各位前辈,谢谢

以上是 如何MongoDB中对数组进行$lookup连表,将连接获得的数据放入添加到数组 的全部内容, 来源链接: utcz.com/p/937410.html

回到顶部