i want to merge some fields who has same number and number i want to match last 9 digits and and i want validations = separate docs which has invalid address of ‘default_address.phone’ or has null or undefined and after group i want also this docs and grouped dos code provided
result = await Customer.aggregate([
{ $match: { storeId: { $in: stores } } },
{
$project: {
...selectedFields,
customerName: { $concat: ["$first_name", " ", "$last_name"] },
},
},
{
$facet: {
groupedDocs: [
{
$match: {
"default_address.phone": { $exists: true, $ne: "" },
},
},
{
$match: {
$expr: {
$gte: [
{ $strLenCP: { $ifNull: ["$default_address.phone", ""] } },
9,
],
},
},
},
{
$sort: { _id: 1 },
},
{
$group: {
_id: {
$substrCP: [
"$default_address.phone",
{ $subtract: [{ $strLenCP: "$default_address.phone" }, 9] },
9,
],
},
orders_count: { $sum: "$orders_count" },
total_spent: { $sum: { $toDouble: "$total_spent" } },
last_order_name: { $last: "$last_order_name" },
last_order_id: { $last: "$last_order_id" },
...groupProjection,
},
},
{
$set: {
_id: "$docId",
},
},
{
$unset: "docId",
},
],
filteredDocs: [
// {
// $match: {
// "default_address.phone": { $exists: false, $eq: "" },
// },
// },
{
$match: {
$expr: {
$lt: [
{ $strLenCP: { $ifNull: ["$default_address.phone", ""] } },
9,
],
},
},
},
],
},
},
{
$project: {
docs: { $concatArrays: ["$filteredDocs", "$groupedDocs"] },
},
},
{ $unwind: "$docs" },
{ $replaceRoot: { newRoot: "$docs" } },
{ $match: filter },
{
$unset: "customerName",
},
{
$sort: { _id: -1 },
},
{
$facet: {
data: [{ $skip: startIndex }, { $limit: limit }],
count: [{ $count: "total" }],
},
},
])``