[英]Get true or false ( only value not array or object ) from mongodb lookup aggregation
I am trying to make a function that returns if a user is a favorite or not.我正在尝试制作一个 function ,如果用户喜欢或不喜欢,它会返回。
I am using MongoDB aggregate on User model with lookout with favourites model ( in which all favourite user has saved ) with pipeline and $project我在用户 model 上使用 MongoDB 聚合与收藏夹 model (其中所有最喜欢的用户已保存)与管道和 $project
here is the MongoDB aggregate function query这是 MongoDB 聚合 function 查询
await User.aggregate([
{
$match: {
_id: ObjectId(_id),
},
},
{
$lookup: {
from: 'userportfolios',
localField: '_id',
foreignField: 'user',
as: 'user_portfolios',
},
},
{
$lookup: {
from: 'favourites',
pipeline: [
{
$match: {
user: ObjectId(data.user._id),
favourites: {
$elemMatch: {
$eq: ObjectId(_id),
},
},
},
},
{
$project: {
_id: 0,
is_favourite: {
$cond: [
{ $ifNull: ['$is_favourite', false] },
{ $literal: true },
{ $literal: false },
],
},
},
},
],
as: 'is_favourite',
},
},
]);
and I am getting this result我得到了这个结果
[
{
"_id": "602b5078e8eb5339e0134351",
"is_active": true,
"is_admin": false,
"is_block": false,
"user_type": "company",
"firstName": "Sagar",
"lastName": "Davara",
"mobileNumber": "*******",
"email": "s*********@gmail.com",
"password": "b7370338e54b1cb051be0dd54eba2f7f",
"verificationCode": "210768",
"createdAt": "2021-02-16T04:56:24.091Z",
"updatedAt": "2021-02-16T04:56:24.091Z",
"user_portfolios": [],
"is_favourite": [
{
"is_favourite": false
}
]
}
]
but I want to get is_favourite: true
instead of an array of object I need this output from mongodb但我想得到is_favourite: true
而不是 object 的数组我需要来自 mongodb 的 output
[
{
"_id": "602b5078e8eb5339e0134351",
"is_active": true,
"is_admin": false,
"is_block": false,
"user_type": "company",
"firstName": "Sagar",
"lastName": "Davara",
"mobileNumber": "6353764283",
"email": "sagardspeed3@gmail.com",
"password": "b7370338e54b1cb051be0dd54eba2f7f",
"verificationCode": "210768",
"createdAt": "2021-02-16T04:56:24.091Z",
"updatedAt": "2021-02-16T04:56:24.091Z",
"user_portfolios": [],
"is_favourite": false
}
]
Just add below stage after $lookup
stage:只需在$lookup
阶段之后添加以下阶段:
{
$addFields: {
is_favourite: { $arrayElemAt: ["$is_favourite.is_favourite", 0] }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.