Time Series Metadata add field - Mongo 6.0 copy from non-meta field

Hi,
I am trying with no luck in Mongo6.0 to add a field to Metadata. For each document, this field is going to have value of another field (called registerId) from the same document. The existing Metadata object contains 2 fields siteId and organizationId. I am looking to add one more field to Metadata called registerId by copying registerId field for each document.

Tried multiple ways. All of them add the field registerId to Metadata as expected but the value is string ‘$registerId’ instead of the value of registerId field.

db.litmusDataPoint.aggregate([{$set:{'Metadata.registerId':'$registerId'}}])

db.litmusDataPoint.updateMany({}, {$set: {"Metadata.registerId": "$registerId"}})

Is it not possible to dynamically set value of metaData filed in Mongo 6.0?

Hey @Pari_Dhanakoti,

Welcome to the MongoDB Community!

Let us know if you have any further questions!

Regards,
Kushagra

Hi, Appreciate your insights. Looking at the link provided , $set is allowed. As in my original post, second command I have tried uses update many with $set. However, the results are same. It adds the meta field but sets it to string “$registerId” instead of value of the field registerId.

db.litmusDataPoint.updateMany({}, {$set: {"Metadata.registerId": "$registerId"}})

Hi @Pari_Dhanakoti,

So, when you execute the $set operator even on a regular collection, it will return the same results.

For example, let’s consider you have the following documents in regular collection:

{
  "_id": 1,
  "name": "Product A",
  "price": 20,
}

And when you execute the command:

db.collections.updateMany({}, {$set: {"Metadata.price": "$price"}})

it will return the following result:

{
  "_id": 1,
  "name": "Product A",
  "price": 20,
  "Metadata": {
    "price": "$price"
  }
}

So, to address this, we have implemented an update with an aggregation pipeline that adds the price value to 'Metadata.price'.

db.books.updateMany( {},[ {
      $set: { "Metadata.price": "$price" } } ] )

returning the following output:

{
  "_id": 1,
  "name": "Product A",
  "price": 20,
  "Metadata": {
    "price": 20
  }
}

But as you know presently this feature is not available for the Time Series Collection.

Hope it answers your question.

Regards,
Kushagra