Database Can';t$在$group之后展开文档
我在学习Mongo,但我不了解聚合函数。我有一个用户可以发表许多不同类型的文章,我通过blogName匹配该用户,然后$lookup查找所有具有匹配用户ID的文章 在那之后,我被难住了。如果我放松,不分组,那么我会得到混乱的合并文档,但我想要的只是帖子 如果我在$unwind之后进行分组,那么文档将返回到对象中 此代码:Database Can';t$在$group之后展开文档,database,mongodb,mongoose,mongodb-query,aggregation-framework,Database,Mongodb,Mongoose,Mongodb Query,Aggregation Framework,我在学习Mongo,但我不了解聚合函数。我有一个用户可以发表许多不同类型的文章,我通过blogName匹配该用户,然后$lookup查找所有具有匹配用户ID的文章 在那之后,我被难住了。如果我放松,不分组,那么我会得到混乱的合并文档,但我想要的只是帖子 如果我在$unwind之后进行分组,那么文档将返回到对象中 此代码: return User .aggregate([ { $match: {
return User
.aggregate([
{
$match: {
blogName: blogName
}
},
{
$lookup: {
from: 'posts',
localField: '_id',
foreignField: 'user',
as: 'posts'
}
},
{
$unwind: "$posts"
},
{
$group: {
_id: "$_id",
'posts': { $push: { fields: '$posts' } }
}
},
给我这个:
[
{
_id: 6065e579bf709d81274cc51e,
posts: [ [Object], [Object], [Object], [Object] ]
}
]
[
{ _id: 6065e579bf709d81274cc51e, posts: { fields: [Object] } },
{ _id: 6065e579bf709d81274cc51e, posts: { fields: [Object] } },
{ _id: 6065e579bf709d81274cc51e, posts: { fields: [Object] } },
{ _id: 6065e579bf709d81274cc51e, posts: { fields: [Object] } }
]
在$group
之后添加第二个$unwind
,只会得到以下结果:
[
{
_id: 6065e579bf709d81274cc51e,
posts: [ [Object], [Object], [Object], [Object] ]
}
]
[
{ _id: 6065e579bf709d81274cc51e, posts: { fields: [Object] } },
{ _id: 6065e579bf709d81274cc51e, posts: { fields: [Object] } },
{ _id: 6065e579bf709d81274cc51e, posts: { fields: [Object] } },
{ _id: 6065e579bf709d81274cc51e, posts: { fields: [Object] } }
]
这离我想要的更远
我只想要那些帖子。如果我可以$diswind这个数组中的帖子,那么我可以从那里处理所有的事情。我对此有什么不理解
更新1:
如果我只是这样使用$project:
return User
.aggregate([
{
$match: {
blogName: blogName
}
},
{
$lookup: {
from: 'posts',
localField: '_id',
foreignField: 'user',
as: 'posts'
}
},
{
$unwind: "$posts"
},
{
$project: {
"_id": 0,
"posts": "$posts"
}
},
我可以得到这个数组:
[
{
posts: {
_id: 60664856447970128fee597b,
descriptionImages: [],
tags: [],
likes: [],
kind: 'TextPost',
createdAt: 2021-04-01T22:25:26.531Z,
updatedAt: 2021-04-01T22:25:26.531Z,
title: '',
body: '',
user: 6065e579bf709d81274cc51e,
__v: 0
}
},
{
posts: {
_id: 60664925d2548912dc960e05,
mainImages: [],
descriptionImages: [],
tags: [],
likes: [],
kind: 'PhotoPost',
createdAt: 2021-04-01T22:28:53.179Z,
updatedAt: 2021-04-01T22:28:53.179Z,
user: 6065e579bf709d81274cc51e,
description: '',
__v: 0
}
},
{
posts: {
_id: 6066495f347bb812fd6dc703,
mainImages: [],
descriptionImages: [],
tags: [],
likes: [],
kind: 'PhotoPost',
createdAt: 2021-04-01T22:29:51.815Z,
updatedAt: 2021-04-01T22:29:51.815Z,
user: 6065e579bf709d81274cc51e,
description: '',
__v: 0
}
},
{
posts: {
_id: 60664961347bb812fd6dc704,
descriptionImages: [],
tags: [],
likes: [],
kind: 'TextPost',
createdAt: 2021-04-01T22:29:53.385Z,
updatedAt: 2021-04-01T22:29:53.385Z,
title: '',
body: '',
user: 6065e579bf709d81274cc51e,
__v: 0
}
}
]
但现在我很困惑如何摆脱额外的筑巢水平。我只需要每个post对象,而不需要posts下的其他嵌套。Demo-
使用
用指定的文档替换输入文档。该操作将替换输入文档中的所有现有字段,包括_id字段。您可以将现有嵌入文档升级到顶层,或创建新文档进行升级(请参见示例)
请添加示例数据并共享链接预期输出是什么?