如何从 MongoDB 获得预期的输出?
How to get expected output from MongoDB?
我是 MongoDB 聚合的新手。我没有得到想要的输出
我从聚合中得到的输出:-
[
{tweet:{key:value}},
{tweet:{key:value}},
{tweet:{key:value}},
{tweet:{key:value}},
]
但我想要管道的以下输出:-
[
{key:value},
{key:value},
{key:value},
]
最后,管道我是 运行:-
const pipeline = [[
{
$match: {
$expr: {
$in: [
Mongoose.Types.ObjectId(userid), '$likedBy.user'
]
}
}
}, {
$lookup: {
from: 'tweets',
localField: 'tweet',
foreignField: '_id',
as: 'tweet'
}
}, {
$unwind: {
path: '$tweet'
}
}, {
$lookup: {
from: 'users',
localField: 'tweet.user',
foreignField: '_id',
as: 'user'
}
}, {
$unwind: {
path: '$user'
}
}, {
$addFields: {
'tweet.user': '$user'
}
},
{
$addFields: {
'tweet.isLiked': true,
}
},{
$project:{
tweet:1,
}
},
]
];
const likedTweets = await TweetLike.aggregate(pipeline)
我知道我可以用 javascript 做到这一点,但我想用管道做到这一点
您可以将上一个项目阶段替换为以下内容以实现您的需要:
{$project:{key:"$tweet.key"}}
回答我自己的问题
我想 return sub-document 所以我找到了这个
我所要做的就是使用
{
$replaceRoot: {newRoot: "$tweet"}
}
对我有用
我是 MongoDB 聚合的新手。我没有得到想要的输出 我从聚合中得到的输出:-
[
{tweet:{key:value}},
{tweet:{key:value}},
{tweet:{key:value}},
{tweet:{key:value}},
]
但我想要管道的以下输出:-
[
{key:value},
{key:value},
{key:value},
]
最后,管道我是 运行:-
const pipeline = [[
{
$match: {
$expr: {
$in: [
Mongoose.Types.ObjectId(userid), '$likedBy.user'
]
}
}
}, {
$lookup: {
from: 'tweets',
localField: 'tweet',
foreignField: '_id',
as: 'tweet'
}
}, {
$unwind: {
path: '$tweet'
}
}, {
$lookup: {
from: 'users',
localField: 'tweet.user',
foreignField: '_id',
as: 'user'
}
}, {
$unwind: {
path: '$user'
}
}, {
$addFields: {
'tweet.user': '$user'
}
},
{
$addFields: {
'tweet.isLiked': true,
}
},{
$project:{
tweet:1,
}
},
]
];
const likedTweets = await TweetLike.aggregate(pipeline)
我知道我可以用 javascript 做到这一点,但我想用管道做到这一点
您可以将上一个项目阶段替换为以下内容以实现您的需要:
{$project:{key:"$tweet.key"}}
回答我自己的问题
我想 return sub-document 所以我找到了这个
我所要做的就是使用
{
$replaceRoot: {newRoot: "$tweet"}
}
对我有用