【发布时间】:2021-09-08 12:22:14
【问题描述】:
我有两个集合 users 和 profiles。我正在使用以下查询实现搜索:
User.aggregate(
[
{
$match: {
_id: { $ne: req.user.id },
isDogSitter: { $eq: true },
profileId: { $exists: true }
}},
{
$project: {
firstName: 1,
lastName: 1,
email: 1,
isDogSitter: 1,
profileId: 1,
}},
{
$lookup: {
from: "profiles",
pipeline: [
{
$project: {
__v: 0,
availableDays: 0,
}},
{
$match: {
city: search
}}
],
as: "profileId",
}}
],
(error, result) => {
console.log("RESULT ", result);
}
);
这样做是它在profiles 集合中搜索city,当没有搜索匹配时,profileId 变成一个空数组。我真正想要的是,如果profileId 是一个空数组,那么我也不想返回文档中的其他字段。它应该清空数组。以下是我当前返回的结果。
RESULT [
{
_id: 60cabe38e26d8b3e50a9db21,
isDogSitter: true,
firstName: 'Test',
lastName: 'Sitter',
email: 'test@user.com',
profileId: []
}
]
【问题讨论】:
标签: mongodb mongodb-query aggregation-framework