[英]Add field if another document matching exist with MongoDB & Mongoose
I have in my DB a collection of Posts with basic informations like:我的数据库中有一组包含基本信息的帖子,例如:
Posts = {
_id: '',
title '',
desc '',
...
}
i also have a Likes collection like (document are created or deleted of user like the post):我也有一个喜欢的集合,比如(创建或删除用户喜欢的文件):
Likes = {
_id: '',
user_id: '',
post_id: '',
}
and the goal would be that when i get a list of Posts , to add a field Liked who show true/false if a document Like match or not, and also the number of match in the Like collection (this i know how to) like:目标是,当我获得Posts列表时,添加一个字段Liked ,如果文档Like匹配,则显示 true/false,以及Like集合中的匹配数(我知道如何)喜欢:
Posts = [{
_id: '',
title '',
desc '',
liked: true,
likes: 5,
...
}, ...]
i've used $lookup
& $addFields
but can join only with one value so far.我已经使用
$lookup
和$addFields
但到目前为止只能加入一个值。 In my case i want one specific document and filtered by 2 fields (user_id, post_id).在我的情况下,我想要一个特定的文档并按 2 个字段(user_id、post_id)过滤。
What i get so far:到目前为止我得到了什么:
const posts = await posts.aggregate
([
{
$lookup: {
from: 'likes',
localField: '_id',
foreignField: 'post_id',
as: 'likes'
}
},
{ $match: {
user_id: mongoose.Types.ObjectId(req.params.id),
} },
{
$addFields: {
likes:
{ $size: "$likes" } // here nb of likes
}
}
])
Try with this one试试这个
db.getCollection('post').aggregate([
{
$lookup: {
from: 'likes',
localField: '_id',
foreignField: 'post_id',
as: 'likes'
}
},
{
$addFields:{
size:{$size:"$likes"},
liked:
{$size: {
$filter: {
input: "$likes",
as: "item",
cond: { $eq: [ "$$item.user_id", ObjectId("5f2a38ad61a591cf96d58f6a") ] }
}
}
}
}
},
{
$addFields:{
liked:{
$cond:[{$eq:["$liked",0]},false,true]
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.