![](/img/trans.png)
[英]How can I create new fields in return results and set values in them on the basis of conditions using Mongoose?
[英]Mongoose: Trying to filter users based on two fields using $and filters them as if I am using $or
我有這個 function 應該返回給定月份中沒有在該月注冊的活躍用戶。 即:留存用戶
const getActiveUsersInAMonthWereNotRegisteredInThatMonth = async (
month,
year
) => {
let response = {
active_users_who_were_not_registered_that_month: null,
};
// Group login event in a month by user id
const login_project_stage = {
$project: {
year: { $year: "$date" },
month: { $month: "$date" },
user: "$user",
category: "$category",
},
};
const login_filter_stage = {
$match: {
year: parseInt(year),
month: parseInt(month),
category: "LOGIN",
},
};
const active_users_group_stage = {
$group: {
_id: "$user",
number_of_logins: { $sum: 1 },
},
};
const look_up_user_stage = {
$lookup: {
from: "users",
localField: "_id",
foreignField: "_id",
as: "user",
},
};
const project_user_stage = {
$project: {
user_id: { $arrayElemAt: ["$user._id", 0] },
registration_month: { $month: { $arrayElemAt: ["$user.date", 0] } },
registration_year: { $year: { $arrayElemAt: ["$user.date", 0] } },
},
};
const user_filter_stage = {
$match: {
$and: [
{
registration_year: {
$ne: parseInt(year),
},
registration_month: {
$ne: parseInt(month),
},
},
],
},
};
const user_sum_stage = {
$group: {
_id: null,
total_number_of_active_users_who_did_not_register_this_month: { $sum: 1 },
users: {
$push: "$$ROOT",
},
},
};
const login_pipeline = [
login_project_stage,
login_filter_stage,
active_users_group_stage,
look_up_user_stage,
project_user_stage,
user_filter_stage,
user_sum_stage,
];
const active_users_who_were_not_registered_that_month =
await History.aggregate(login_pipeline);
response.active_users_who_were_not_registered_that_month =
active_users_who_were_not_registered_that_month;
return response;
};
問題是這個階段:
const user_filter_stage = {
$match: {
$and: [
{
registration_year: {
$ne: parseInt(year),
},
registration_month: {
$ne: parseInt(month),
},
},
],
},
};
它不會過濾掉在那個月和年注冊的用戶,而是過濾掉在那個月或年注冊的用戶。
例如,如果month=7
和year=2022
,任何在 2022 年或7 月(第 7 個月)注冊的用戶將不會被退回。
但是,我只希望它過濾 2022 年和7 月(第 7 個月)注冊的用戶。
知道如何解決這個問題嗎?
這是解決方案:
$nor: [
{
registration_year: parseInt(year),
registration_month: parseInt(month),
},
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.