Aggregation pipeline $densify with value for step inside range can come from document?

For example I have a field called billingFrequencyInMonths which should act as step for densifying the document, How do I achieve this?

Hey @Anusha_S,

Welcome to the MongoDB Community Forums! :leaves:

In order to understand the requirement better, could you please share the below information for us to be better able to help you out:

  • Sample documents
  • MongoDB version used
  • The query you are executing
  • Expected output/result

Regards,
Satyam

MongoDB version is 6
Sample document is
{
“type”:“LONG_TERM”,
“billingFrequencyDetails”:{
“billingFrequency”:“OTHER”,
“billingFrequencyInMonths”:3,
},
“startDate”:{
“$date”:{
“$numberLong”:“1653868800000”
}
},
“contractEndDate”:{
“$date”:{
“$numberLong”:“1685404800000”
}
},
“contractLengthInMonths”:12,
“status”:“UPCOMING_RENEWAL”
}

Query is :
{
monthlyBilledContracts: [
{
$match: {
“billingFrequencyDetails.billingFrequency”:
“MONTHLY”,
},
},
{
$addFields: {
amountPerBilling: {$toDouble : “$cost”},
timeStamp: [
“$startDate”,
“$contractEndDate”,
],
},
},
{
$unwind: {
path: “$timeStamp”,
preserveNullAndEmptyArrays: true,
},
},
{
$densify: {
field: “timeStamp”,
partitionByFields: [“_id”],
range: {
step: 1,
unit: “month”,
bounds: “partition”,
},
},
},
],
quarterlyBilledContracts: [
{
$match: {
“billingFrequencyDetails.billingFrequency”:
“QUARTERLY”,
},
},
{
$addFields: {
numberOfBillingPerContract: {
$divide: [
{
$dateDiff: {
startDate: “$startDate”,
endDate: “$contractEndDate”,
unit: “quarter”,
},
},
1,
],
},
},
},
{
$addFields: {
amountPerBilling: {
$divide: [
“$cost”,
“$numberOfBillingPerContract”,
],
},
timeStamp: [
“$startDate”,
“$contractEndDate”,
],
},
},
{
$unwind: {
path: “$timeStamp”,
preserveNullAndEmptyArrays: true,
},
},
{
$densify: {
field: “timeStamp”,
partitionByFields: [“_id”],
range: {
step: 1,
unit: “quarter”,
bounds: “partition”,
},
},
},
],
}
Very similar to this monthly and quarterly billed i also need custom billed contract where i want the document to be densified from start date to contract end date monthly where the frequesncy in month is decided by billingFrequencyDetails.billingFrequencyInMonths. If billingFrequencyInMonths is 3 then i want the document to be densified every 3 months. Meaning
$densify: {
field: “timeStamp”,
partitionByFields: [“_id”],
range: {
step: 3,
unit: “quarter”,
bounds: “partition”,
},

here step should be 3. How do i get this 3 from the collection into step field of desnify?

What i need is
$densify: {
field: “timeStamp”,
partitionByFields: [“_id”],
range: {
step: ‘$billingFrequencyDetails.billingFrequencyInMonths’, ----> Not able to do this
unit: “quarter”,
bounds: “partition”,
},