Home > Net >  aggregate with dynamic field path- mongo DB and nodeJS
aggregate with dynamic field path- mongo DB and nodeJS

Time:08-11

I have a collection- 'products' that contains the following documents:

{
  productName: "computer",
  updateAt: "2022-07-12T12:44:47.485Z",
  createAt: ""2022-06-12T10:34:03.485Z",
  changeAt: ""2022-09-12T10:39:40.485Z"
}

I want to create an aggregation that convert the field "updateAt" from string to date.

for this, I created this aggregation:

db.products.aggregate([{
        $set: {
          updateAt: {
            $dateFromString: {
              dateString: '$updateAt'
            }
          }
        },
      },
      {
        $out: 'products'
      }]
    )

It works fine for this need, but as you can see I specified the field path "updateAt" in a hard coded way.I want to use the above aggregation in a dynamic way- considering I have an array of fields that I want to change:

const fields = ['updateAt', 'createAt', 'changeAt']

I want to loop over the fields array and use each field as a fieldPath so I can transfer the field name to the aggregation, something like that-

fields.forEech(field -> {
  db.products.aggregate([{
        $set: {
          `${field}`: {
            $dateFromString: {
              dateString: `$${field}`
            }
          }
        },
      },
      {
        $out: 'products'
      }]
    )
}

As you can understand it's not working for me....
How can I achieve my goal?

CodePudding user response:

You have some errors in your nodejs function, also, aggregate method returns a Promise, so you will need to wait for it, to resolve before moving further.

Try this:

const fields = ['updateAt', 'createAt', 'changeAt']
for(let i=0; i < fields.length; i  ) {
  let field = fields[i];
  await db.products.aggregate([{
        "$set": {
          [field]: {
            "$dateFromString": {
              "dateString": `$${field}`
            }
          }
        },
      },
      {
        "$out": 'products'
      }]
    )
}

Also, make the function containing this piece of code async.

  • Related