如何解决MongoDB聚合:将数组属性展平为根数组
我正在开发一个功能,该功能使用$graphLookUp
递归查找注释线程,并且我几乎拥有它。 (尽管有些复杂,但是可以正常工作!)
我需要的最后一步是:
与其将嵌套的posteriorThread
作为根数组($$ROOT
)的属性,而不仅仅是将其合并到根本身上。
- 注册码:
const posteriorThread = await Comment.aggregate([
{
$match: {
_id: post.threadDescendant
}
},{
$graphLookup: {
from: 'baseposts',startWith: '$threadDescendant',connectFromField: 'threadDescendant',connectToField: '_id',as: 'posteriorThread'
}
},{
$unwind: '$posteriorThread'
},{
$sort: { 'posteriorThread.depth': 1 }
},{
$group: {
_id: '$_id',posteriorThread: { $push: '$posteriorThread' },root: { $first: '$$ROOT' }
}
},{
$project: {
'root.posteriorThread': 0
}
},{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
posteriorThread: '$posteriorThread'
},'$root'
]
}
}
}
]);
- 当前输出
OUTPUT: posteriorThread
[
{
_id: '5f7eab40575e6fc56ee07604',onModel: 'BasePost',depth: 1,user: '5f5da45245c07cc06e51b09f',text: 'thread 0',isThread: true,threadDescendant: '5f7eabad575e6fc56ee07607',posteriorThread: [
{
_id: '5f7eabad575e6fc56ee07607',onModel: 'Comment',depth: 2,text: 'thread 1',threadDescendant: '5f7eac82575e6fc56ee07609'
},{
_id: '5f7eac82575e6fc56ee07609',depth: 3,text: 'thread 2',isThread: true
}
]
}
];
- 期望的输出
OUTPUT: posteriorThread
[
{
_id: '5f7eab40575e6fc56ee07604',threadDescendant: '5f7eabad575e6fc56ee07607'
},{
_id: '5f7eabad575e6fc56ee07607',threadDescendant: '5f7eac82575e6fc56ee07609'
},{
_id: '5f7eac82575e6fc56ee07609',isThread: true
}
];
我可以在常规js中完成聚合后完成此操作,但我希望在聚合中全部完成。
需要替换的部分是mergeObjects
位,并替换为其他内容或group
聚合并采取不同的策略,但是我不确定要放什么位置。
另外,如果您还有其他建议要使这种清洁器更清洁,我会很高兴。
谢谢。
解决方法
这确实具有挑战性。至少对于我来说。真的很有趣。让我们尝试一下我的解决方案。希望它能起作用。
db.test.aggregate([
// PREVIOSU STEPS YOU ALREADY DID
{
$group: {
_id: "$_id",items: {$push: "$$ROOT"},subItems: {$first: "$posteriorThread"}
}
},{
$project: {
"items.posteriorThread": 0
}
},{
$addFields: {
allItems: {
$concatArrays: ["$items","$subItems"]
}
}
},{
$group: {
_id: null,mergedItems: {$push: "$allItems"}
}
},{
$unwind: "$mergedItems"
},{
$replaceRoot: {
newRoot: "$mergedItems"
}
}
])
,
感谢@Sunil K Samanta指导我朝正确的方向发展。这不是最漂亮的解决方案,但确实为我提供了正确的解决方案。
const posteriorThread = await Comment.aggregate([
{
$match: {
_id: post.threadDescendant
}
},{
$graphLookup: {
from: 'baseposts',startWith: '$threadDescendant',connectFromField: 'threadDescendant',connectToField: '_id',as: 'posteriorThread'
}
},{
$unwind: '$posteriorThread'
},{
$sort: { 'posteriorThread.depth': 1 }
},{
$group: {
_id: '$_id',items: { $push: '$$ROOT.posteriorThread' },root: { $push: '$$ROOT' },},{
$project: {
items: 1,root: { $slice: ['$$ROOT.root',1] },{
$project: {
'root.posteriorThread': 0,{
$addFields: {
allItems: {
$concatArrays: ['$root','$items'],{
$replaceRoot: {
newRoot: {
full_posterior: '$$ROOT.allItems',])
)[0].full_posterior;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。