我是 MongoDB 和貓鼬的新手。
我正在嘗試從資料庫中檢索整個物件層次結構陣列作為 JSON。
通過搜索,我學會了如何在沒有陣列的情況下將嵌套查找與 3 個子級別進行分組,但問題是我找不到處理嵌套陣列的方法。
這就是我正在努力解決的問題。
用戶:
[
{
_id: ObjectId("a1"),
username: "user1",
name: "name1"
},
{
_id: ObjectId("a2"),
username: "user2",
name: "name2"
},
{
_id: ObjectId("a3"),
username: "user2",
name: "name2"
},
...
]
回復:
[
{
_id: ObjectId("a"),
author: {ObjectId("a3")},
title: {"Reply1"};
body: {"Hello World!"}
},
{
_id: ObjectId("b"),
author: {ObjectId("a1")},
title: {"Reply2"};
body: {"Hello World!"}
},
{
_id: ObjectId("c"),
author: {ObjectId("a2")},
title: {"Reply3"};
body: {"Hello World!"}
},
{
_id: ObjectId("d"),
author: {ObjectId("a2")},
title: {"Reply4"};
body: {"Hello World!"}
}
...
]
郵政:
[
//First post
{
_id: ObjectId("0"),
title: 'post title',
author: {ObjectId("a1")},
reply: [{ObjectId("a")}, {ObjectId("b")}, ...],
},
//Second Post
{
_id: ObjectId("1"),
title: 'post title2',
author: {ObjectId("a2")},
reply: [{ObjectId("c")}, {ObjectId("d")}, ...],
},
...
]
預期示例:
[
//First post
{
_id: ObjectId("0"),
title: 'post title',
author: {
_id: ObjectId("a1"),
username: "user1",
name: "name1"
},
reply: [{
_id: ObjectId("a"),
author: {
_id: ObjectId("a3"),
username: "user2",
name: "name2"
},
title: {"Reply1"},
body: {"Hello World!"}
},
{
_id: ObjectId("b"),
author: {
_id: ObjectId("a1"),
username: "user1",
name: "name1"
},
title: {"Reply2"};
body: {"Hello World!"}
},
...
],
},
{
//Second post
},
...
]
這是我使用的代碼。
posts = await Post.aggregate([{
$match: searchQuery
},
{
$lookup: {
from: 'users',
localField: 'author',
foreignField: '_id',
as: 'author'
}
},
{
$lookup: {
from: 'replies',
localField: 'reply',
foreignField: '_id',
as: 'reply'
}
},
{
$unwind: '$author',
},
{
$lookup: {
from: 'users',
localField: 'reply.author',
foreignField: '_id',
as: 'reply.author'
}
},
{
$project: {
title: 1,
author: 1,
reply: 1
}
},
]).exec();
如果我想獲得預期的示例,我應該如何更改代碼?謝謝你。
uj5u.com熱心網友回復:
這是一種方法。很多"$lookup"for author of post, replyto the post, author ids of reply,然后是作者檔案匹配_id。
db.post.aggregate([
{
"$lookup": {
"from": "user",
"localField": "author",
"foreignField": "_id",
"as": "author"
}
},
{
"$set": {
"author": {
"$first": "$author"
}
}
},
{
"$lookup": {
"from": "reply",
"localField": "reply",
"foreignField": "_id",
"as": "reply"
}
},
{
"$lookup": {
"from": "user",
"localField": "reply.author",
"foreignField": "_id",
"as": "replyAuthors"
}
},
{
"$project": {
"title": 1,
"author": 1,
"reply": {
"$map": {
"input": "$reply",
"as": "repObj",
"in": {
"$mergeObjects": [
"$$repObj",
{
"author": {
"$first": {
"$filter": {
"input": "$replyAuthors",
"as": "repA",
"cond": {
"$eq": [
"$$repA._id",
"$$repObj.author"
]
}
}
}
}
}
]
}
}
}
}
}
])
在mongoplayground.net上試試。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/424019.html
標籤:javascript 节点.js mongodb 猫鼬
