【发布时间】:2020-01-24 08:11:32
【问题描述】:
假设我有这两个系列
book: {
_id: 'aaa'
name: 'Book 1',
chapters: [
0: {
_id: 'chapter0',
name: 'Chapter 1',
pages: [
0: {
_id: 'page0',
name: 'Page 1',
paragraphs: [
0: {
_id: 'paragraph0',
name: 'Paragraph 1',
bookmarks: [
0: {sentence: 3, reader: 'Foo'},
1: {sentence: 8, reader: 'Bar'},
2: {sentence: 14, reader: 'John'}
]
}
]
}
]
}
]
}
book: {
_id: 'bbb'
name: 'Book 2',
chapters: [
0: {
_id: 'chapter0',
name: 'Chapter 1',
pages: [
0: {
_id: 'page0',
name: 'Page 1',
paragraphs: [
0: {
_id: 'paragraph0',
name: 'Paragraph 1',
bookmarks: []
},
1: {
_id: 'paragraph1',
name: 'Paragraph 2',
bookmarks: [
0: {sentence: 2, reader: 'George'},
1: {sentence: 1, reader: 'Paul'},
2: {sentence: 76, reader: 'John'},
3: {sentence: 54, reader: 'Ringo'}
]
}
]
}
]
}
]
}
我希望能够在获得结果时提取数组bookmarks 并将它们附加到book 集合中。像这样的东西会很好:
{
id: 'aaa'
name: 'Book 1'
bookmarks: [{...}, {...}, {...}] //since the first book has 3 bookmarks
},
{
id: 'bbb'
name: 'Book 2'
bookmarks: [{...}, {...}, {...}, {...}] //since the second book has 4 bookmarks
},
如果没有书签,它应该是这样的:
{
id: 'aaa'
name: 'Book 1'
bookmarks: [{...}, {...}, {...}] //since the first book has 3 bookmarks
},
{
id: 'bbb'
name: 'Book 2'
bookmarks: [{...}, {...}, {...}, {...}] //since the second book has 4 bookmarks
},
{
id: 'ccc'
name: 'Book 3'
bookmarks: [] //third book does not have bookmarks for example
},
我已尝试使用此代码进行聚合,但它只是将每本书的每个书签分开并将其推送到对象中。
return yield Books.aggregate()
.unwind('chapters')
.unwind('chapters.pages')
.unwind('chapters.pages.paragraphs')
.unwind('chapters.pages.paragraphs.bookmarks')
.group({
_id: '$_id',
books: {
$push: {
_id: '$_id',
name: '$name',
bookmarks: '$chapters.pages.paragraphs.bookmarks'
}
}
}).exec()
有人能指出我正确的方向吗?谢谢!
【问题讨论】:
标签: mongodb mongoose nosql aggregation-framework