Home > Mobile >  MongoDB - dateAsString returns [object object]
MongoDB - dateAsString returns [object object]

Time:02-28

I am trying to add a new field to all of the documents in my collection .

The new field should be a concat of the form doc.name "_" doc.created

I wrote the following code -

db.test.find({}).forEach(function(doc) {
    doc.externalId= doc.name   "_"   { "$dateToString": { "format": "%Y-%m-%d %H-%M", "date": doc.created } }
    db.test.save(doc);
})

And the result is -

{ 
    "_id" : ObjectId("621b63bec07bb9761216d08a"), 
    "name" : "test1", 
    "created" : ISODate("2021-07-12T08:22:16.688 0000"), 
    "externalId" : "test1_[object Object]"
}
{ 
    "_id" : ObjectId("621b63bec07bb9761216d08b"), 
    "name" : "test2", 
    "created" : ISODate("2021-08-12T08:22:16.688 0000"), 
    "externalId" : "test2_[object Object]"
}
{ 
    "_id" : ObjectId("621b63bec07bb9761216d08c"), 
    "name" : "test3", 
    "created" : ISODate("2021-09-12T08:22:16.688 0000"), 
    "externalId" : "test3_[object Object]"
}

I tried simply concating with the existing creation date, but I cannot control the returned date's format -

db.test.find({}).forEach(function(doc) {
    doc.externalId= doc.name   "_"   doc.created;
    db.test.save(doc);
})

output -

{ 
    "_id" : ObjectId("621b6413c07bb9761216d08d"), 
    "name" : "test1", 
    "created" : ISODate("2021-07-12T08:22:16.688 0000"), 
    "externalId" : "test1_Mon Jul 12 2021 11:22:16 GMT 0300 (Jerusalem Daylight Time)"
}
{ 
    "_id" : ObjectId("621b6413c07bb9761216d08e"), 
    "name" : "test2", 
    "created" : ISODate("2021-08-12T08:22:16.688 0000"), 
    "externalId" : "test2_Thu Aug 12 2021 11:22:16 GMT 0300 (Jerusalem Daylight Time)"
}
{ 
    "_id" : ObjectId("621b6413c07bb9761216d08f"), 
    "name" : "test3", 
    "created" : ISODate("2021-09-12T08:22:16.688 0000"), 
    "externalId" : "test3_Sun Sep 12 2021 11:22:16 GMT 0300 (Jerusalem Daylight Time)"
}

How can I get the string value of this object? I would like it to return something like an ISODate - 2021-07-12T08:22:16.688 or even what it currently returns just without the GTM time - Sun Sep 12 2021 11:22:16 (without the GMT 0300 (Jerusalem Daylight Time) suffix)

Thanks

Edit:

Mongo version 3.4.19

CodePudding user response:

Move the externalId logic as projection.

db.test.find({},
{
  name: 1,
  created: 1,
  externalId: {
    $concat: [
      "$name",
      "_",
      {
        "$dateToString": {
          "format": "%Y-%m-%dT%H:%M:%S.%L",
          "date": "$created"
        }
      }
    ]
  }
})
.forEach(...)

Sample Mongo Playground


Another approach is to use toISOString method;

db.test.find({}).forEach(function(doc) {
    let created = doc.created.toISOString().split('Z')[0];
    doc.externalId= doc.name   "_"   created;
    db.test.save(doc);
})
  • Related